Constructor in a subclass of UIView?

I have generated an application based on the Utility App template for Iphone. In my MainView class I have written som initialisation code that isn't called:
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
NSLog(@"MainView instanse initialised");
// Initialization code
NSLog(@"MainView instanse initialised");
return self;
None of the log messages appears, how is UIView being initialised?
Thomas

init will never be called, because the constructor for UIView is initWithFrame. If you create a UIView-subclass object then you will do so by calling alloc on the class and then initWithFrame on the result of alloc.
On the other hand, if you are relying on the object coming into existence because it was specified in Interface Builder, then the object isn't, conceptually, being created at all when your program starts. The idea is that Interface Builder created the object, archived it to the NIB file, and your program is now un-archiving it from there.
Your awakeFromNib method is called after the object has been un-archived from the NIB file. I've tended to use this on the Mac; on the iPhone I've tended to use the UIViewController's viewDidLoad method instead.
Here is what the documentation has to say on the subject of awakeFromNib:
+During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type. Objects that conform to the NSCoding protocol (including all subclasses of UIView and UIViewController) are initialized using their initWithCoder: method. All objects that do not conform to the NSCoding protocol are initialized using their init method. After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects. It then calls the awakeFromNib method of the objects. For more detailed information about the steps followed during the nib-loading process, see Nib Files and Cocoa in Resource Programming Guide.+
The "Nib Files and Cocoa" article is long and complex and, as far as subclasses of UIView are concerned, untrue.

Similar Messages

  • Why does the child class need to implement the parent classes constructor?/

    As I was playing around with some code I came across this point :
    First Class
    public class A {
         public int x;
         A(int i){
              x=i;
              System.out.println("A is initialised");
    }Second Class extending it :
    public class B extends A{
         private int y;
       // Why do I need this constructor to call parents constructor?
      // My guess is so that when i make an object of class B referring to class A it should make sense?
         B(int i) {                     
              super(i); 
              y=test;
    public static void main(String args[]){
          A a = new A(1);
          A b = new B(1); make an object of class B referring to class A it should work!!
          B c = new B(2);
          B d =(B) new A(2);  --> gives class cast exception!
    }I am little confused here, Can someone throw more light on it.
    Thanks

    You don't override constructors. However, every class, in it's constructor, must call some constructor from the class it's extending. In most cases this is simply super(). However, if your class does not have a default constructor (i.e. you've declared any other constructor, or the sub class does not have access to it, I.E. you've declared it private) then you must include a call to some other constructor in the super class. The constructor in the subclass does not have to be the same as the super class one, but you do have to invoke a constructor from the super class. I.E.
    class A {
      A(int i) {}
    class B extends A {
      B(String b) {
        super(0);
    }

  • Constructors and init'd vars, order of execution

    // vartest.java
    // Demonstrates some odd behavior concerning initialized variables.
    abstract class testobject {
      abstract public void output();
      testobject() {
        output(); // Simple enough; we need to output stuff during this object's construction.
    public class vartest {
    public int outernumber=42; // This value is clearly set before the constructor runs.
    vartest() {
      System.out.println("The outer number is "+outernumber+", should be 42."); // This works as expected.
    // Now we do the same thing in an inner class:
      testobject test=new testobject() { // Anonymous subclass that defines output().
        public int innernumber=9; // Is this value set before or after the following constructor runs?
        public void output() {
          System.out.println("The inner number is "+innernumber+", should be 9."); // I get a 0 here instead of a 9!
      }; // End of that anonymous subclass.
    // Something went wrong there, but let's try that output again, just because.
      test.output(); // Here I get the 9, but I needed the 9 earlier!
    } // End of vartest() constructor.
    public static void main(String[] args) {
      vartest vt=new vartest();
    }Here is the output I get from this program:The outer number is 42, should be 42.
    The inner number is 0, should be 9.
    The inner number is 9, should be 9.This scenario is a greatly simplified excerpt, by the way, from the program I've been trying to develop. Specifically, my program uses heavily compressed streaming data; each piece of this data is stored in a subclass of an abstract decompressor class which expands the desired data in the constructor. Each subclass contains a different output() function that determines what to do with this data while it's being extracted. This has worked well for me in other languages. However, this strategy fails in Java if any initialization of variables is required, because the initialization, for some reason, doesn't occur until after the constructor is called, and by then it's too late!
    This seems weird and counter-intuitive to me. Repeated Google searches yielded no clue as to why this happens. Did I find a bug, or is there some mistake in my code that's eluding me?

    Yup, I found the example code at the end of section 12.5, and it describes exactly what I'm encountering. I did have to read that section a few times, but now I understand why it makes sense for Java to work this way.
    So it's not really a bug, just an unwanted side-effect of my slightly-too-inventive design. (As expected.)
    Now that I've got that part figured out, it occurs to me that I can move the variable initialization into a method which would be called by the superclass's constructor before it begins the output. This'll work just like the previous variable initialization, except now it'll be called in the desired order. For example, if I changed my code thusly:
    abstract class testobject {
      abstract public void output();
      public void init() { } // Added this function, it'll be overridden later
      testobject() {
        init();
        output();
      testobject test=new testobject() {
        public int innernumber; // Assignment moved to init() method
        public void init() {
          innernumber=9; // That should do it!
        public void output() {
          System.out.println("The inner number is "+innernumber+", should be 9.");
        }This does exactly what I want.
    I actually feel a little unintelligent now for not having come up with this obvious workaround before. (But I take a look at everything else I'm doing and I feel better. =D )
    Well, this problem is solved, and I also learned something interesting about the "guts" of Java today. Thanks for the help, guys! I hope some day to be able to show you something impressive!

  • Execution of class_constructors in subclass

    hi all, i'm new to abap objects but the testing the code below puzzles me.  can anyone explain why if i execute WRITE b=>d, the sub class_constructor is not executed?  i would expect that after executing the super c-c, the sub c-c is next.  as expected, only the super c-c is executed for WRITE a=>d.
    i had read, once a subclass is addressed, the c-c is executed if it hasn't been yet, after all unperformed super c-c's are executed.  but why when addressing b=>d not perform it?
    CLASS a DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA d TYPE c VALUE 'D'.
        CLASS-METHODS class_constructor.
    ENDCLASS.
    CLASS b DEFINITION INHERITING FROM a.
      PUBLIC SECTION.
        CLASS-METHODS class_constructor..
    ENDCLASS.
    CLASS a IMPLEMENTATION.
      METHOD class_constructor.
        WRITE:/ 'Superclass constructor'.
      ENDMETHOD.
    ENDCLASS.
    CLASS b IMPLEMENTATION.
      METHOD class_constructor.
        WRITE:/ 'Subclass constructor'.
      ENDMETHOD.
    ENDCLASS.

    Hi,
    b=>d  is a static component. There is no need to instantiante a class b (= calling the constructor) and this means that the class to the class_constructor is deferred as well. The only thing which is for shure is that the class_constructor of B is called before the constructor of B. But up to now this is not necessary.
    If you do the following the class_constructor of B is called.
    report  zzztest.
    class a definition.
      public section.
        class-data d type c value 'D'.
        class-methods class_constructor.
        methods constructor.
    endclass.                    "a DEFINITION
    class b definition inheriting from a.
      public section.
        class-methods class_constructor.
        methods constructor.
    endclass.                    "b DEFINITION
    class a implementation.
      method class_constructor.
        write:/ 'Superclass class constructor'.
      endmethod.                    "class_constructor
      method constructor.
        write:/ 'Superclass constructor'.
      endmethod.                    "class_constructor
    endclass.                    "a IMPLEMENTATION
    class b implementation.
      method class_constructor.
        write:/ 'Subclass class constructor'.
      endmethod.                    "class_constructor
      method constructor.
        super->constructor( ).
        write:/ 'Subclass constructor'.
      endmethod.                    "class_constructor
    endclass.                    "b IMPLEMENTATION
    data l_b type ref to b.
    end-of-selection.
      write / 'Start'.
      create object l_b.
      write / b=>d.
    The output is:
    Superclass class constructor
    Start
    Subclass class constructor
    Superclass constructor
    Subclass constructor
    D
    End
    Please be aware the a class_constructor is only called once for each class. The constructor is called for each object.
    Hope this helps.
    Regards Matthias

  • Abstract classes and constructors - cannot call abs. methods in CONSTRUCTOR

    Let me explain the scenario:
    I'm building a program in which I need to read a file (among other things) and I intend to use object orientation to it's fullest in doing so. I thought of creating an abstract FILE class which has the commonalities, and two subclasses SERVER_FILE and PC_FILE, which implement the abstract method GET_CONTENTS in different ways (OPEN DATASET / GUI_UPLOAD), same for the CHOOSE method which allows to select the file from it's corresponding source.
    Initially I've used an interface but since another tasks like setting the file path are common for both, switched to an ABSTRACT class.
    Now, the problem is, from the main code I intend to use a FILE reference to handle either type of file. At the instantiation moment I'd like the path attribute to be set; if it was not set by parameter, i'd like to call the CHOOSE method which is abstract for the superclass. Since this is common for either subclass, I need a way to code it once in the superclass. But I get an error because the CHOOSE method is abstract.
    This is the problem code (extracts):
    *       CLASS lcl_file DEFINITION
    CLASS lcl_file DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
          constructor
            IMPORTING
              i_path  TYPE string OPTIONAL
            EXCEPTIONS
              no_path_chosen,
          get_contents ABSTRACT
            RETURNING
              value(rt_contents) TYPE string_table
            EXCEPTIONS
              read_error.
      PROTECTED SECTION.
        DATA:
          _v_path        TYPE string.
        METHODS:
          choose ABSTRACT
            EXCEPTIONS
              no_path_chosen,
          set_path
            IMPORTING
              i_path  TYPE string.
    ENDCLASS.                    "lcl_file DEFINITION
    *       CLASS lcl_file IMPLEMENTATION
    CLASS lcl_file IMPLEMENTATION.
      METHOD constructor.
        IF i_path IS SUPPLIED.
          CALL METHOD set_path
            EXPORTING
              i_path = i_path.
        ELSE.
    *---->>>> PROBLEM CALL - CAN'T BE DONE!!
          CALL METHOD choose
            EXCEPTIONS
              no_path_chosen = 1.
          IF sy-subrc = 1.
            RAISE no_path_chosen.
          ENDIF.
        ENDIF.
      ENDMETHOD.                    "constructor
      METHOD set_path.
        _v_path = i_path.
      ENDMETHOD.                    "set_path
    ENDCLASS.                    "lcl_file IMPLEMENTATION
    *       CLASS lcl_server_file DEFINITION
    CLASS lcl_server_file DEFINITION
                          INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION.
      PROTECTED SECTION.
        METHODS:
          choose       REDEFINITION.
    ENDCLASS.                    "lcl_server_file  DEFINITIO
    *       CLASS lcl_server_file IMPLEMENTATION
    CLASS lcl_server_file IMPLEMENTATION.
      METHOD choose.
        DATA:
          l_i_path     TYPE dxfields-longpath,
          l_o_path     TYPE dxfields-longpath.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'A'  " Application server
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path <> l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "choose
      METHOD get_contents.
        DATA: l_line   LIKE LINE OF rt_contents,
              l_osmsg  TYPE string.
        CHECK NOT _v_path IS INITIAL.
        OPEN DATASET _v_path FOR INPUT
                                 IN TEXT MODE
                                 MESSAGE l_osmsg.
        IF sy-subrc <> 0.
          MESSAGE e000(oo) WITH l_osmsg
                           RAISING read_error.
        ELSE.
          DO.
            READ DATASET _v_path INTO l_line.
            IF sy-subrc = 0.
              APPEND l_line TO rt_contents.
            ELSE.
              EXIT.
            ENDIF.
          ENDDO.
          CLOSE DATASET _v_path.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_server_file IMPLEMENTATION
    *       CLASS lcl_pc_file DEFINITION
    CLASS lcl_pc_file  DEFINITION
                       INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION.
      PROTECTED SECTION.
        METHODS:
          choose       REDEFINITION.
    ENDCLASS.                    "lcl_pc_file  DEFINITIO
    *       CLASS lcl_pc_file IMPLEMENTATION
    CLASS lcl_pc_file IMPLEMENTATION.
      METHOD choose.
        DATA:
          l_i_path     TYPE dxfields-longpath VALUE 'C:\',
          l_o_path     TYPE dxfields-longpath.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'P'  " PC
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path <> l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "choose
      METHOD get_contents.
        CHECK NOT _v_path IS INITIAL.
        CALL METHOD cl_gui_frontend_services=>gui_upload
          EXPORTING
            filename                = _v_path
          CHANGING
            data_tab                = rt_contents
          EXCEPTIONS
            file_open_error         = 1
            file_read_error         = 2
            no_batch                = 3
            gui_refuse_filetransfer = 4
            invalid_type            = 5
            no_authority            = 6
            unknown_error           = 7
            bad_data_format         = 8
            header_not_allowed      = 9
            separator_not_allowed   = 10
            header_too_long         = 11
            unknown_dp_error        = 12
            access_denied           = 13
            dp_out_of_memory        = 14
            disk_full               = 15
            dp_timeout              = 16
            OTHERS                  = 17.
        IF sy-subrc <> 0.
          RAISE read_error.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_pc_file IMPLEMENTATION
    * Data
    DATA: gr_file          TYPE REF TO lcl_file.
    * Main Program
    START-OF-SELECTION.
    *   Get text lines from file
        IF p_srv = abap_true.
          CREATE OBJECT gr_file
            TYPE
              lcl_server_file
            EXCEPTIONS
              no_path_chosen  = 1.
        ELSE.
          CREATE OBJECT gr_file
            TYPE
              lcl_pc_file
            EXCEPTIONS
              no_path_chosen = 1.
        ENDIF.
    On a 4.6c system this code gave me a dump, while on my NW7.0 SP it doesn't even activate with the following error:
    You cannot call abstract methods in the "CONSTRUCTOR" method.
    - Following some suggestions from Java forums i've tried to define the constructor in the base class as PROTECTED or PRIVATE instead, then calling super->constructor from the subclasses, but I get this error in german:
    Sichtbarkeit des Konstruktors darf nicht spezieller als die Sichtbarkeit der Instanzerzeugung (CREATE-Zuzatz) sein.
    which Altavista translates like:
    Visibility of the constructor may not be more special than the
    visibility of the instance production (CREATE Zuzatz).
    - I've also thought of defining the CHOOSE method as a class (not instance) one, then calling it before creating the file object which maybe solves the problem, but I see that approach more "procedural oriented" which i'm trying to avoid.
    - Of course I could define a constructor for each subclass, but both would have exactly the same code.
    I'm really lost on how should I code this. My main focus is on avoiding code dupplication.
    I hope someone with more OO experience can see what I'm trying to do and sheds some light.
    Many thanks for reading all this!

    Dear Alejandro,
        When i saw your code, you are trying to access an astract method CHOOSE(which is actually implemented in sub class) from the constructor of the base class which is not possible.  By this time, we don't know which sub class it is refering to, so it gives an error.   I see two solutions for this..
    1.  To define constructor in sub class and call the choose method from the consturctor of the sub class(which in this case is reputation of the same again for each sub class)
    2.  Remove the calling of choose method from the constructor of the main class and call it separately(after creating the object).   By now we know which sub class we are refering to.   I would have designed the program in the following way.
    *       CLASS lcl_file DEFINITION
    CLASS lcl_file DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
          constructor
            IMPORTING
              i_path  TYPE string OPTIONAL
            EXCEPTIONS
              no_path_chosen,
          get_contents ABSTRACT
            RETURNING
              value(rt_contents) TYPE string_table
            EXCEPTIONS
              read_errorm,
          set_path ABSTRACT
            EXCEPTIONS
              no_path_chosen.
      PROTECTED SECTION.
        DATA:
          _v_path        TYPE string.
    *    METHODS:
    *      choose ABSTRACT
    *        EXCEPTIONS
    *          no_path_chosen,
    *      set_path ABSTRACT
    *        IMPORTING
    *          i_path  TYPE string.
    ENDCLASS.                    "lcl_file DEFINITION
    *       CLASS lcl_file IMPLEMENTATION
    CLASS lcl_file IMPLEMENTATION.
      METHOD constructor.
        IF i_path IS SUPPLIED.
          _v_path = i_path.
    *      CALL METHOD set_path
    *        EXPORTING
    *          i_path = i_path.
    *    ELSE.
    **---->>>> PROBLEM CALL - CAN'T BE DONE!!
    *      CALL METHOD choose
    *        EXCEPTIONS
    *          no_path_chosen = 1.
    *      IF sy-subrc = 1.
    *        RAISE no_path_chosen.
    *      ENDIF.
        ENDIF.
      ENDMETHOD.                    "constructor
    * METHOD set_path.
    *    _v_path = i_path.
    * ENDMETHOD.                    "set_path
    ENDCLASS.                    "lcl_file IMPLEMENTATION
    *       CLASS lcl_server_file DEFINITION
    CLASS lcl_server_file DEFINITION
                          INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION,
          set_path     REDEFINITION.
    *  PROTECTED SECTION.
    *    METHODS:
    *      choose       REDEFINITION.
    ENDCLASS.                    "lcl_server_file  DEFINITIO
    *       CLASS lcl_server_file IMPLEMENTATION
    CLASS lcl_server_file IMPLEMENTATION.
      METHOD set_path.
        DATA:
          l_i_path     TYPE dxfields-longpath,
          l_o_path     TYPE dxfields-longpath.
        CHECK _v_path IS INITIAL.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'A'  " Application server
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path  = l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "set_path
      METHOD get_contents.
        DATA: l_line   LIKE LINE OF rt_contents,
              l_osmsg  TYPE string.
        CHECK NOT _v_path IS INITIAL.
    *    OPEN DATASET _v_path FOR INPUT
    *                             IN TEXT MODE
    *                             MESSAGE l_osmsg.
        IF sy-subrc  = 0.
    *      MESSAGE e000(oo) WITH l_osmsg
    *                       RAISING read_error.
        ELSE.
          DO.
            READ DATASET _v_path INTO l_line.
            IF sy-subrc = 0.
              APPEND l_line TO rt_contents.
            ELSE.
              EXIT.
            ENDIF.
          ENDDO.
          CLOSE DATASET _v_path.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_server_file IMPLEMENTATION
    *       CLASS lcl_pc_file DEFINITION
    CLASS lcl_pc_file  DEFINITION
                       INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION,
          set_path     REDEFINITION.
    *  PROTECTED SECTION.
    *    METHODS:
    *      choose       REDEFINITION.
    ENDCLASS.                    "lcl_pc_file  DEFINITIO
    *       CLASS lcl_pc_file IMPLEMENTATION
    CLASS lcl_pc_file IMPLEMENTATION.
      METHOD set_path.
        DATA:
          l_i_path     TYPE dxfields-longpath VALUE 'C:\',
          l_o_path     TYPE dxfields-longpath.
        CHECK _v_path IS INITIAL.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'P'  " PC
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path  = l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "set_path
      METHOD get_contents.
        CHECK NOT _v_path IS INITIAL.
        CALL METHOD cl_gui_frontend_services=>gui_upload
          EXPORTING
            filename                = _v_path
          CHANGING
            data_tab                = rt_contents
          EXCEPTIONS
            file_open_error         = 1
            file_read_error         = 2
            no_batch                = 3
            gui_refuse_filetransfer = 4
            invalid_type            = 5
            no_authority            = 6
            unknown_error           = 7
            bad_data_format         = 8
            header_not_allowed      = 9
            separator_not_allowed   = 10
            header_too_long         = 11
            unknown_dp_error        = 12
            access_denied           = 13
            dp_out_of_memory        = 14
            disk_full               = 15
            dp_timeout              = 16
            OTHERS                  = 17.
        IF sy-subrc  = 0.
    *      RAISE read_error.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_pc_file IMPLEMENTATION
    * Data
    DATA: gr_file          TYPE REF TO lcl_file.
    * Main Program
    START-OF-SELECTION.
    *   Get text lines from file
      IF abap_true = abap_true.
        CREATE OBJECT gr_file
          TYPE
            lcl_server_file
          EXCEPTIONS
            no_path_chosen  = 1.
      ELSE.
        CREATE OBJECT gr_file
          TYPE
            lcl_pc_file
          EXCEPTIONS
            no_path_chosen = 1.
      ENDIF.
      gr_file->set_path( ).
    Regards
    Kesava
    Edited by: Kesava Chandra Rao on Mar 19, 2008 11:44 AM

  • Why it is needed to invoke parent constructor?

    public class AAA
    public AAA(int a) {  }
    public class BBB extends AAA
    public BBB(int a) { super(a); }
    public BBB() {  }
    It gives an error in the second constructor of class BBB. Why? Why Java requires AAA to have an AAA() constructor???
    Maciek

    public class AAA
    public AAA(int a) {  }
    public class BBB extends AAA
    public BBB(int a) { super(a); }
    public BBB() {  }
    It gives an error in the second constructor of class
    BBB. Why? Because you have not explicitely called a parent constructor, the compiler will add an implicit call to the no-args parent constructor thus:
    super();But the no-args constructor does not exist in the superclass!
    The compiler only creates a default constructor if you do not explicitely declare any constructors, so since you have declared a constructor that takes an argument, and have not declared a constructor that takes no arguments, AAA does not have a no-args constructor.
    Why Java requires AAA to have an AAA()
    constructor???It doesn't - it only requires it to have at least one constructor. But the code you have in BBB tries to call the non-existent AAA() constructor. You must either explicitely declare the no-args constructor, or explicitely call an existing constructor from every constructor in every subclass.

  • Super class default constructor

    Hello,
    I want to clear some confusion. I am studying for the exam. In this particular book an example shows that
    Super class has 2 constructor
    public abc() and public abc(int n)
    Sub class has 2 constructor
    public xyz() and public xyz(int n)
    now when an instance is created for the subclass
    xyz t = new xyz(1)
    It will invoke the super class no argument constructor eventhough a default constructor exist in subclass?
    Regards,
    adil

    Here are the rules for constructors--"ctors" because I'm lazy. Also, because I'm lazy, "super(...)" and "this(...)" mean any super or this call, regardless of how many args it takes, including those that take no args.
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Inheritance Issue - constructor

    Okay, I hope you guys can help me out of this. I currently have an interface designed, with a class inheriting its information. Here is the sample code for reference:
    ArrayStack
    public class ArrayStack
        implements AnotherInterface
        public ArrayStack(int stacksize)
            stack = new String[stacksize];
        public boolean isFull()
            return top == stack.length;
    }Now the problem arises when I want to create a new class which inherits the ArrayStack. Here is a sample code of what I have wrote up:
    public class checkSize extends ArrayStack
        public checkSize()
    }I'm just trying to get my head around inheritance, but this code keeps giving me the error "cannot find symbol - constructor". Can anyone point me to the right direction or tell me what I can do? Any help would be greatly appreciated!

    Connex007 wrote:
    Melanie_Green wrote:
    So as suggested you can either call another constructor or you can create a default constructor in your superclass,Now that's where I'm getting confused on - what other constructor can I call?There is only one other constructor to call in the super class.
    Remember that the first line of every constructor is either an explicit or implicit call to another constructor. If you do not explicitly call another constructor then super() is inserted during compile time, and the default constructor that has no parameters of the superclass is called.
    Furthermore any class that does not explicitly extend another class, extends Object. So as I stated previously if the first line of the any constructor in this class is not a call to another constructor, then the compiler will insert super() which will invoke the default constructor of Object.
    Now in your scenario you are using inheritance, you have a subclass extending a superclass. Note that you have not defined a default constructor in the super class, which for example is defined in Object. So inside your subclass, if you do not call another constructor on the first line, then again the compiler will insert a call to super(). The call to super() from the subclass is dependent on the superclass having defined a default no parameter constructor. However in your case the superclass does not have such a constructor defined. Therefore you are still required to instantiate every class in the inheritance tree, either explicitly or implicitly.
    If you are still weary at this point, think of it this way. If A extends B extends C. When an object of type A is instantiated, a constructor of A then B then C is called so that C is instantiated first, then B, then A. This is reflective of instantiated in a top down method so that each subclass is instantiated correctly. Since A extends B, and B can potentially be instantiated in one or more ways, you still need to define how both A and B are instantiated.
    So relating this back to your problem, what are all the possible ways in which your superclass can be instantiated? We can eliminate the default constructor and assume that we must specify on the first line of the constructor contained in the subclass that a call to a constructor in the subclass or superclass occurs. If we invoke a constructor in the same class, in the subclass, then either this constructor calls a constructor in the super class, or it calls a constructor that in turn will tinkle its way up to calling a constructor in the superclass.
    Mel

  • Overloading constructor question

    The following douse not seem to work:-
    class A {
         A( int i ) {
              System.out.println( "A constructor" + i );
    class B {
         B( int i ) {
              System.out.println( "B constructor" + i );
    class C extends A {
         C () { // line 17
              System.out.println( "C constructor" );
         public static void main( String[] args ) {
              C c = new C();
    It complaines at line 17
    A(int) in A cannot be applied to ()
    C () {
    ^
    This has totaly bafeld be. I thought it was OK to add overloaded constructors in inheratid classes but it seems to be complaining that I am replacing C(int) wit C(), i.e. the constructor in the subclass has diferent arguments. surly this should simply add an overloaded constructer?
    Ben

    The first statement in every constructor must be a call to either a) another constructor in that class or b) a constructor of the super class. If you do not specify a call to either, then the compiler automatically will insert a call to the no argument constructor of the super class. Since there isn't a no-arg constructor in A, the compiler complains that you are calling the A(int) constructor with no arguments. You need to either add a no argument constructor to A, or you need to call the A(int) constructor from the C constructor with some default value.
    In case you didn't know, to call a super constructor from a subclass, you use the super keyword.
    Example:
    class A {
        A(int i) {}
    class B extends A {
        B() {
            super(2);  //This call the A(int) constructor.
    }

  • The rules of Java constructors

    A constructor with no parameters will automatically call super(). If I extend an object with a parametered constructor, I need to manually enter that constructor into my subclass constructor "super(a, b)".
    What then of non extended objects? In this non-extended object if I make a constructor that takes parameters doesn't it automatically make calls to super(). It has to to construct an Object object no?
    I haven't read anything regarding this specific behaviour. I was hoping someone could confirm or deny my suspicions.

    jverd wrote:
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.If that would have been a question I wonder how many responds will provide the correct answer.

  • Interface Builder and subclassing

    Is it possible for me to have the outlet in Interface Builder pointing to a superclass... then in the code using that interface to point to a subclass?
    So for example, suppose I'm setting up an interface in Interface Builder with a HumanView (let's say this is a subclass of UIView)... suppose this is like a character in an MMORPG... and you're customizing your chaacter...
    and correspondingly in my code I have:
    IBOutlet HumanView *character;
    But I'm uncertain whether this view will be a female or male character... In my code I have two subclass of HumanView... FemaleView and MaleView... each with its own unique instance variables and methods...
    Is it possible for me to decide in the program to have make "character" a FemaleView or MaleView?
    Thanks.
    Message was edited by: iphonemediaman

    Not a problem. I did realize I should add one minor clarification.
    1) You can cast a quadralateral to a square in one instance. When you know that actual object (the structure in memory) is a square.
    So, to be complete, you can safely cast a the square to a quadralateral all day long -- you know that a square is always a quadralateral. But if you are going to cast the quadralateral to a square, you should make sure you actually have a square object. The compiler will let you do it (might show a warning), but you could end up trying to reference pieces of a square that may not actually be part of the actual object. aka (in pseudo code):
    // no issues with these two alloc/inits
    Quad *foo = (Quad *)[[Square alloc] init];
    Quad *bar = (Quad *)[[Rectangle alloc] init];
    // both would return 4
    [foo numSides];
    [bar numSides];
    // if setSideLength is only a method on a Square, then
    // first line works fine
    [(Square*)foo setSideLength:20.0];
    // this line, however, will likely give a compiler warning and then
    // an EXC_BAD* error during runtime -- bar is not actually a square
    // in memory, despite what you are telling the compiler
    [(Square*)bar setSideLength:20.0];
    I hope I didn't conuse the issue -- but wanted to clarify.
    Cheers,
    George

  • Question about constructors and inheritance

    Hello:
    I have these classes:
    public class TIntP4
        protected int val=0;
        public TIntP4(){val=0;}
        public TIntP4(int var)throws Exception
            if(var<0){throw new Exception("TIntP4: value must be positive: "+var);}
            val=var;
        public TIntP4(String var)throws Exception
            this(Integer.parseInt(var));
        public String toString()
            return val+"";
    public class TVF extends TIntP4
    }Using those clases, if I try to compile this:
    TVF  inst=new TVF("12");I get a compiler error: TVF(String) constructor can not be found. I wonder why constructor is not inherited, or if there is a way to avoid this problem without having to add the constructor to the subclass:
    public class TVF extends TIntP4
         public TVF (String var)throws Exception
              super(var);
    }Thanks!!

    I guess that it would not help adding the default constructor:
    public class TVF extends TIntP4
         public TVF ()
               super();
         public TVF (String var)throws Exception
              super(var);
    }The point is that if I had in my super class 4 constructors, should I implement them all in the subclass although I just call the super class constructors?
    Thanks again!

  • How to get visible UIView bounds

    I'm using a UIViewController that displays a view, has a tab bar and a navigation controller.
    Within loadView, I set view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    However, view.frame shows a height of 460 (without accounting for the space taken up by the nav bar and the tab bar)
    Does anyone know how to find out the visible rect height for the UIView (i.e. excluding space taken up by the nav bar and the tab bar)
    (The docs mention a visibleRect property for CALayer, but the header files don't include this property)

    no, I haven't subclassed the UIView.
    I'm using the default UIView created by the UIViewController's loadView (the view is just a container for other views)
    I was hoping that it will be possible to figure out the UIView's visible rect.
    However, as an alternative, does anyone know how to determine the height of the tabbar used in a UITabbarController ?
    (I could hardcode this value as a last resort, but I'm hoping that there is a programmatic way to get the height of the tabbar. Note that I've created a UITabBarController and added view controllers and tabbaritems, but the tabbaritem doesn't give me its corresponding UITabBar).

  • Starting threads in constructors

    Hi,
    This is kind of a general question. I have a class which initializes a thread within a constructor. e.g.,
    Class A {
             //Initialize thread prerequisites
            String name;
             Thread th;
           classConstructor(String threadName){
                    name = threadName;
                    th = new Thread(this, name);
                    System.out.println( "New Thread: " +th);          
                    th.start() ;
    }Is this the right way of using threads? Or should threads be started from the main method? What are the merits/demerits in these two approaches?
    Thanks!

    You can start threads from anywhere. After all, you're just creating another Java object and calling the start method on it.
    However, there are places where you shouldn't start threads. Unfortunately, in constructors of non-final classes is one of those places. And here's why...
    If you subclass your class, the subclass constructor will begin by calling one of the constructors in your class (either implicitly or explicitly). In this case, your constructor will create and begin a thread. That thread could potentially call methods on this new object instance (especially as in your case you have passed this to the thread, so it looks likely that it will). The problem is, because we're talking about threads, the thread might call the methods on your class before your constructor or the subclass constructor has completed, and you would therefore be calling methods on an incomplete object which might cause issues.
    For example:
    public abstract class A {
      public A() {
        // create and start thread here
      public abstract int getSomething();
    public class B extends A {
      private static int something;
      public B() {
        // implicitly calls A()
        something = 1;
      public int getSomething() {
        return something;
    }Now, if the thread you started calls getSomething(), the return value might be 0, or it might be 1, depending on how the thread executes in relation to the original thread which is executing the constructors.

  • Overriding Constructor Method

    Hello,
    I want to write a class that heritances behaviour and porpoerties of the superclass. Is it possible to execute the methods of the superclass in the subclass? Instead I could write a method in the superclass and call it inside constructor of the subclass, but that seems like a trick to me.

    Is it possible to execute the methods of the superclass in the
    subclass? Instead I could write a method in the superclass and call it
    inside constructor of the subclass, but that seems like a trick to me.
    If you are talking about calling super class constructor in subclass, you can do that:
    public function SubClassConstructor(){
         super();
    If you need to call function of superclass, well, you have to write it in superclass, right? Just make it either public or protected.

Maybe you are looking for

  • Error while accessing portal via internet

    Hi all, I am having problems when accessing portal through internet. I have installed NW04 SR1(WAS, EP & KM). Then I created some iviews and pages. Now <u>when I open the portal through internet(using its ip address)</u> and try to access PCD, it is

  • LR rotates images as they were at the upload

    Hi everybody I went back to a folder I haven't been looking for about 3-4 months. After I located the folder from the external disk all the images opened,  with my surprise, without the rotation I have set at the time so I had to to do it all again.

  • Help with Flex preloading and transitions please

    I downloaded and installed Flex Builder 3, and I think I have my slideshow project about 75% finished. It's the last 25% that I can't figure out, regarding preloading and transitions. Can someone take a look at the code below and see if you can help

  • Before Report Function

    Hello, I have the following function witch I need to run before report I mean when ever I press on the submit button (GO). The value returned from the function should be stored in an item i.e P2_Begining_Balance. function BeforeReport return boolean

  • Missing Metadata from my movies/tv progs since update

    Hello, I've updated one of my 2nd gen apple tv's today. Since the update; the movies and tv programs that I've converted from my dvd collection onto my laptop no longer display details like "description" when you select them in the apple menu. Conten