Constructor of a superclass

Hi all
Tell me something about this question plz
"Does a class inherit the constructors of its superclass?"
Thanx in advance.

if you mean:
public class A {
   public A() {}
   public A(int x, int y) {}
public class B extends A {
   public B() {}
}does B have "B(int x, int y)", the answer is no

Similar Messages

  • Does extending a class require a hand-entered constructor in superclass?

    Hello,
    Trying to extend a class (which doesn't have a main() method, if this matters), I got the following compiler message
    NewInput.java:1: cannot resolve symbol
    symbol : constructor InputFileDeclared ()
    location: class InputFileDeclared
    public class NewInput extends InputFileDeclared
    After I hand-entered a blank constructor to the superclass the subclass have compiled.
    Doesn't a class have a constructor by default?

    If your class has a contructor which takes arguments, then the compiler does not provide you with a no-arg constructor. In this case if you need to have a constructor that takes no arguments then you need to write one.
    If your base class had a constructor like
    public class InputFileRead {
    //Constructor
    public InputFileRead( String fileName ) {
    //Methods
    and you wrote your Derived class with no constructor as
    public class NewInput extends InputFileRead {
    //No constructors
    //Methods
    Now when you write
    NewInput nInp = new NewInput();
    since you have not written any constructor for your new class the compiler will provide you with a default no-args constructor which will call the default constructor of your base class. Since there is no default constructor for your base class, you won't be able to instantiate the derived class.
    You need to write a no-arg constructor for the new class which will then call the appropriate constructor of the base class.
    public class NewInput extends InputFileRead {
    //Constructor
    public NewInput() {
    super( "InputFile.txt" );
    //Methods
    }

  • Error while calling a super class public method in the subclass constructor

    Hi ,
    I have code like this:
    CLASS gacl_applog DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
                create_new_a
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXPORTING  pfx_log_hndl TYPE balloghndl
                   EXCEPTIONS error
    ENDCLASS.
    CLASS gacl_applog IMPLEMENTATION.
      METHOD create_new_a.
        DATA: ls_log TYPE bal_s_log.
      Header aufsetzen
        MOVE pf_extnumber TO ls_log-extnumber.
        ls_log-object     = pf_obj.
        ls_log-subobject  = pf_subobj.
        ls_log-aluser     = sy-uname.
        ls_log-alprog     = sy-repid.
        ls_log-aldate     = sy-datum.
        ls_log-altime     = sy-uzeit.
        ls_log-aldate_del = ls_log-aldate + 1.
        CALL FUNCTION 'BAL_LOG_CREATE'
             EXPORTING
                  i_s_log      = ls_log
             IMPORTING
                  e_log_handle = pfx_log_hndl
             EXCEPTIONS
                  OTHERS       = 1.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID      sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH    sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
      PUBLIC SECTION.
        DATA: log_hndl   TYPE balloghndl READ-ONLY
            , t_log_hndl TYPE bal_t_logh READ-ONLY
        METHODS: constructor
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXCEPTIONS error
               , msg_add      REDEFINITION
               , display      REDEFINITION
    ENDCLASS.
    CLASS gcl_applog_temp IMPLEMENTATION.
      METHOD constructor.
        CALL METHOD create_new_a
               EXPORTING  pf_obj       = pf_obj
                          pf_subobj    = pf_subobj
                          pf_extnumber = pf_extnumber
               IMPORTING  pfx_log_hndl = log_hndl.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
    ' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass…'
    Can you please suggest how to change the code with out affecting the functioanlity.
    Thank you ,
    Lakshmi.

    Hi,
    Call that method by instance of Subclass.   OR
    SUPER-->method.
    Read very useful document
    Constructors
    Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
    The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
    METHODS CONSTRUCTOR
            IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
            EXCEPTIONS.. <ei>.
    and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
    The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
    CLASS-METHODS CLASS_CONSTRUCTOR.
    and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
    Pls. reward if useful....

  • Calling a constructor of an object that extends another object

    suppose you have the source:
    class A {
    public int x = 1;
    public int y = 5;
    public A(){y = 6;)
    class B extends A {
    public B(){}
    public B(int a) { super(a); }
    Now suppose in the main function you say
    B b1 = new B();
    I would think the value of x is 1 which it is, but the value of y is 6, why is this, I did not call the A constructor or does an object call the parameterless constructor of its superclass automatically. If that is the case, it will clarify to me why y gets the value of 6 and not 5.

    Unless you specify a super call, it will be done. The next two constructors are the same:public B () {
        x = 2;
    public B () {
        super ();
        x = 2;
    }Another thing for you to try: remove the A () constructor (but keep the A (int)) and see if B will still compile.
    Kind regards,
    Levi

  • Why do we use super when there is no superclass?

    Hello,
    I have a question about the word "super " and the constructor. I have read about super and the constructor but there is somethong that I do not understand.
    In the example that I am studying there is a constructor calles " public MultiListener()" and there you can see " super" to use a constructor from a superclass. But there is no superclass. Why does super mean here?
    import javax.swing.*;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class MultiListener extends JPanel
                               implements ActionListener {
        JTextArea topTextArea;
        JTextArea bottomTextArea;
        JButton button1, button2;
        final static String newline = "\n";
        public MultiListener() {
            super(new GridBagLayout());
            GridBagLayout gridbag = (GridBagLayout)getLayout();
            GridBagConstraints c = new GridBagConstraints();
            JLabel l = null;
            c.fill = GridBagConstraints.BOTH;
            c.gridwidth = GridBagConstraints.REMAINDER;
            l = new JLabel("What MultiListener hears:");
            gridbag.setConstraints(l, c);
            add(l);
            c.weighty = 1.0;
            topTextArea = new JTextArea();
            topTextArea.setEditable(false);
            JScrollPane topScrollPane = new JScrollPane(topTextArea);
            Dimension preferredSize = new Dimension(200, 75);
            topScrollPane.setPreferredSize(preferredSize);
            gridbag.setConstraints(topScrollPane, c);
            add(topScrollPane);
            c.weightx = 0.0;
            c.weighty = 0.0;
            l = new JLabel("What Eavesdropper hears:");
            gridbag.setConstraints(l, c);
            add(l);
            c.weighty = 1.0;
            bottomTextArea = new JTextArea();
            bottomTextArea.setEditable(false);
            JScrollPane bottomScrollPane = new JScrollPane(bottomTextArea);
            bottomScrollPane.setPreferredSize(preferredSize);
            gridbag.setConstraints(bottomScrollPane, c);
            add(bottomScrollPane);
            c.weightx = 1.0;
            c.weighty = 0.0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 10, 0, 10);
            button1 = new JButton("Blah blah blah");
            gridbag.setConstraints(button1, c);
            add(button1);
            c.gridwidth = GridBagConstraints.REMAINDER;
            button2 = new JButton("You don't say!");
            gridbag.setConstraints(button2, c);
            add(button2);
            button1.addActionListener(this);
            button2.addActionListener(this);
            button2.addActionListener(new Eavesdropper(bottomTextArea));
            setPreferredSize(new Dimension(450, 450));
            setBorder(BorderFactory.createCompoundBorder(
                                    BorderFactory.createMatteBorder(
                                                    1,1,2,2,Color.black),
                                    BorderFactory.createEmptyBorder(5,5,5,5)));
        public void actionPerformed(ActionEvent e) {
            topTextArea.append(e.getActionCommand() + newline);
            topTextArea.setCaretPosition(topTextArea.getDocument().getLength());
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("MultiListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new MultiListener();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    OP wrote:
    >
    Isn't that simplier to use the constructor instead of using "super"? I mean using the constructor jpanel () ?
    >
    You can't call the super class constructor directly if you are trying to construct the sub-class. When you call it directly it will construct an instance of the super class but that instance will NOT be an integral part of the 'MultiListener' sub class you are trying to create.
    So since 'MultiListener' extends JPanel if you call the JPanel constructor directly (not using super) your code constructing a new instance of JPanel but that instance will not be an ancestor of your class that extends JPanel. In fact that constructor call will not execute until AFTER the default call to 'super' that will be made without you even knowing it.
    A 'super' call is ALWAYS made to the super class even if your code doesn't have an explicit call. If your code did not include the line:
    super(new GridBagLayout()); Java would automatically call the public default super class constructor just as if you had written:
    super();If the sub class cannot access a constructor in the super class (e.g. the super class constructor is 'private') your code won't compile.

  • Constructor - cannot find symbol

    Hi all,
    Can anyone please help me with this code? I don't know what's wrong with it.
    class Superclass {
        public int j = 0;   
        public Superclass(String text){  //constructor
            j = 1;
    class Subclass extends Superclass {
        public Subclass(String text){  //constructor - error here: cannot find symbol       
            j = 2;       
        public static void main(String[] args){
            Subclass sub = new Subclass("");
            System.out.println(sub.j);
    }What's wrong with the subclass c'tor? What symbol is it missing?
    Thank you for your replies.

    I'm wondering, why do we need the c'tor from the superclass? Is it because it is not inherited? That's why we need to manually write it? NO. It is because you have not written a no argument constructor in your superclass and compiler is calling it when you actually creating a instance of subclass.
    If there are many other superclass c'tors with different types of arguments, do we have to explicitly write each one of them in the subclass c'tor? Is that correct?NO. You just need to call only one with the parameters that you actually need to pass to superclass.
    If you dont put the super(text); in subclass constructor then too it looks for the superclass constructor while creating a instance of subclass. But since if you are not calling a constructor with arguments[which in now done by super(text)] it will look for a default constructor in your superclass which is no argument constructor. & you dont have any no argument constructor in your Superclass.
    Try you code like this. It will work but in this case you are not passing text to your super class. If you want to pass text then you have to use super(text) in your subclass.
    class Superclass {
        public int j = 0; 
        public Superclass()
        public Superclass(String text){      
            j = 1;
        public Superclass(int count){
            count = 10;
    class Subclass extends Superclass {    
        public Subclass(String text){  
            //super(text);  // have to write this line
            j = 2;       
        public Subclass(int count){
            super(count); // have to write this line also
            count = 15;
        public static void main(String arg[]){
             Subclass  s = new Subclass("e");
    }I hope it helps.

  • Constructor in ooabap

    what is the functionality of the constructor.
    what is the diff b/w static and instance constructor.

    Hi Krishnaveni,
    Static Constructor:
    Static constructors are executed the first time you address a class.  In case you address a static attribute declared in a superclass using the class name of a subclass, only the static constructor of the superclass is executed.  There is only one static constructor.
    Instance Constructor:
    This is the first method which is called when an object is created. There can be a constructor for every instance of an object created.
    Regards,
    Sai

  • Constructor-problem

    public class Three extends Two {
         public static void main(String args[])
              new Three();
    public class Two extends One{
         public Two()
              this(5);
              System.out.println("Constructor of class Two");
         public Two(int x)
              System.out.println("Value of x is   "+x);
    public class One {
         public One()
              System.out.println("Constructor of class One");
    If we do not create any zero argument constructor then the JVM creates one for us and the calls the constructor of the superclass(if any) using super(); and if we do create a zero argument constructor and do not specify super() then it is automatically called.--Is this correct
    If so, when I run class Threethen class Two constructor should be called which calls another constructor of class Two and in this case JVM should not be able to call Parent Constructor One using super() since we have already placed this(5) in the first line of the constructor and I believe super and this cannot be used together.
    So how does constructor of class One get called.

    If we do not create any zero argument constructor
    then the JVM creates one for us and the calls the
    constructor of the superclass(if any) using super();
    and if we do create a zero argument constructor and
    do not specify super() then it is automatically
    called.--Is this correct Mostly. The compiler creates the ctor, I think, not the VM. And it only gets created if you didn't define any ctors for that class.
    Regardless of what ctors you have or have not created, super() will be implicitly called as the first statement of each ctor unless that ctor's first statemen is a call to a super() or a this() ctor (with or without args).
    and in
    this case JVM should not be able to call Parent
    Constructor One using super() since we
    have already placed this(5) in the first line
    of the constructor and I believe super and
    this cannot be used together.Incorrect.
    Three() calls Two() calls Two(5) calls One().
    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.

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

  • Getting Private Constructor of a Class

    Hello all,
    Is there any way to get the private constructor as we get the public constructors using Class.getConstructors() ?
    getConstructors() method is not returning the private constructors, but I need the info about the private constructors also....so if it is possible, please let me know...
    Thanks

    tullio0106 wrote:
    I know, however it's also impossible to invoke private methods but, using reflection, You can.That's a complete different thing. If the private method is not static, it is invoked on the current instance.
    Is it also possible to use private constructors in the same way.
    The problem I'm facing is to create a new instance of a class which extends another class and I need to use a private constructor of the superclass (I've no sources of that superclass).First, the Constructor of a class has to invoke a Constructor of a superclass as the first operation (either implicitely invoking an empty constructor or explicitely). There is no way to do any other operation before that. Second, a reflectively fetched Constructor instance always only can create instances of the class it is defined at (using newInstance()). So, yes, you could get access to a private Constructor. With that, you may be able to create a new instance of the class it is defined for. But that's about it.

  • Where is the constructor?

    Hi,
    I am going through the Swing tutorials and the first sample appication has thrown me for a loop (no pun intended.) In the following code there is an inner class to SwingApplication but why isn't there a constructor such as SwingApplication ();
    import javax.swing.*;          //This is the final package name.
    //import com.sun.java.swing.*; //Used by JDK 1.2 Beta 4 and all
                                   //Swing releases before Swing 1.1 Beta 3.
    import java.awt.*;
    import java.awt.event.*;
    public class SwingApplication {
        private static String labelPrefix = "Number of button clicks: ";
        private int numClicks = 0;
        public Component createComponents() {
            final JLabel label = new JLabel(labelPrefix + "0    ");
            JButton button = new JButton("I'm a Swing button!");
            button.setMnemonic(KeyEvent.VK_I);
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    numClicks++;
                    label.setText(labelPrefix + numClicks);
            label.setLabelFor(button);
             * An easy way to put space between a top-level container
             * and its contents is to put the contents in a JPanel
             * that has an "empty" border.
            JPanel pane = new JPanel();
            pane.setBorder(BorderFactory.createEmptyBorder(
                                            30, //top
                                            30, //left
                                            10, //bottom
                                            30) //right
            pane.setLayout(new GridLayout(0, 1));
            pane.add(button);
            pane.add(label);
            return pane;
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel(
                    UIManager.getCrossPlatformLookAndFeelClassName());
            } catch (Exception e) { }
            //Create the top-level container and add contents to it.
            JFrame frame = new JFrame("SwingApplication");
            SwingApplication app = new SwingApplication();
            Component contents = app.createComponents();
            frame.getContentPane().add(contents, BorderLayout.CENTER);
            //Finish setting up the frame, and show it.
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }Steve Hartfield

    With regard to using super(), I thought that that only
    worked when I use the extend keyword, is it also true
    when I use the import keyword?The import keyword has got nothing to do with this!
    You need to know that there are a number of language constructs that are implicit in Java. Here are the ones I can remember right now:
    1. A class declaration without an extends implicitly extends the Object class. Thus, the following declarations are equvivalent:
    public class A { ... }
    public class A extends Object { ... }2. A class declaration that does not declare any constructors, implicitly declare the default constructor. Thus, the following are equivalent:
    public class A {
    public class A { 
      public A() { }
    }3. A constructor that does not explicitly call the superclass constructor, implicitly calls the no-arg constructor of its superclass (and it is a compile-time error if there is no accessible no-arg constructor in the superclass). Thus, the following are equivalent:
    public class A {
      public A() { }
    public class A { 
      public A() { super(); }
    }4. A reference to an accessable field from the class need not be qualified explicitly with this. Thus, the following are equivalent:
    public class A {
      private int val;
      public int foo() { return val; }
    public class A {
      private int val;
      public int foo() { return this.val; }

  • 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

  • Inheritance constructor question

    Hi
    I am having trouble understanding how the superclasses constructor works in inheritance:
    Please look at the following code:
    public class mySuperClass
         mySuperClass ()
              System.out.println("super1");
    public class myClass extends mySuperClass
         myClass ()
              System.out.println("hello1");
         myClass (int q)
              System.out.println("hello2");
    public static void main(String[] args)
              myClass o = new myClass ();
              myClass o = new myClass (3);
    When I run this program the console results are:
    super1
    hello1
    super1
    hello2
    Why does the constructor of the super class run even when I overload it?
    Thanks
    Aharon

    I think you meant to write "Why does the constructor of the super class run even when I overrideit?"
    And the point is you can't override a constructor (technically, they are not even methods). A constructor in a derived class (MyClass) must call a constructor in its superclass (MySuperClass ). If you do not explicitly call one:
    MyClass (int q) {
        super(...arguments...); // <---
        System.out.println("hello2");
    }There will be an attempt to implicitly to invoke super();

  • Which Constructor Is Being Called?

    Can someone please tell me which constructor is being called in the example below:
    public abstract class SuperClass{
    public SuperClass(String a){ /* constructor code */}
    public class SubClass extends SuperClass{
    public SubClass(String a){super(a);}
    public SubClass(String a, String b){super(a); this.b = b;}
    If I call SubClass(String a, String b), then does the "super(a)" refer to the SubClass(String a) constructor or the SuperClass(String a) constructor?
    Thanks for the help,
    Chris

    super(a) refers to the superclass this(a) refers to the subclass

  • Why is a superclass constructer called automatically?

    I have two simple classes as shown:
    public class Class1 {
    public Class1() {
    System.out.println("Hello World");
    public class Class2 extends Class1 {
    public Class2() {
    static public void main(String[] args) {
    Class2 c2 = new Class2();
    When I run Class2 (i.e. java Class2) it prints out "Hello World". It looks as though the constructor for class 2 is automatically calling the constructor from its superclass (class 1). I thought that you had to specify this with super(). Any Advice?

    this should be in new to java programming.
    anyway, the constructor of the super class need to be call automatically so that the object is in the proper state. suppose you extends from JFrame with class call MyJFrame. when you create your MyJFrame the code that construct the JFrame must be automatically called so that it works fine, after the constructor of the super class get called to initialize it's data then your subclass can initialize its own data. the constructor that is called automatically is the no-argument constructor. so if your super class does not have no-argument constructor you must explicitly call the appropiate super constructor in your subclass. also you cannot create instance of subclass that extends from the super class that has only private no-argument constructor.

Maybe you are looking for

  • How to print new order in odd page or new page

    Hi Experts, I want to print my order layout in oddpage. If any new order comes it should print inthe odd page. Currently its printing Back to back. But I want to print my order layout in oddpage or new page. Any one guide this?? Offering points is ag

  • PDF images that magnify when clicked? (but not in Preview)

    I'm viewing a 3-page PDF document received from elsewhere, using Acrobat 7.0 Standard on a MacBook running OS 10.4.11. The document contains 4 figures. When I run the pointer (the "hand") over 2 of these images, a short horizontal bar with a short ar

  • HT1491 do i need a credit card

    I want to down load a app from the app store on to my ipod the app is free but it brings me to account asking for my credit card how can i by pass that?

  • How to reorganise a RDA application without getting error  RSSTATMAN042?

    Hallo RDA experts, according to this [presentation|https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/40784126-7503-2b10-b586-f6d5acd41f60] SAP  wants us to reorganise a RDA application frequently (see slide 37): "Data has to be dele

  • Quick key launch for next frame in sequenced loop?

    Hi,  I want go quickly through my sequence loop. Is there a key combo for next frame? Thanks Solved! Go to Solution.