Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Consider two classes A and B:

Code Block
titlejava
A.java
 
 public class A{
    public A(){
       // lots of constructor activity.
    }
 }
Code Block
titlejava
B.java
 public class B extends A{
    public B(){}
 }

...

Does the constructor for A get called when a B is constructed?
Or do I need to add the following line to get A constructed?

Code Block
titlejava
B.java
 public B{
    super();
 }

Answer

...

  1. If a java class has no explicit constructor it is assumed to have an "implicit" empty public no-arg constructor:
    Code Block
    titlejava
    MyClass.java
       public MyClass(){}
    
  2. If a constructor does not explicitly call either the super constructor or another of its own constructors (using this(args)) it is assumed to have an "implicit" call to super() as the first line of the constructor. Note also that this() or super() can only be called as the first line of a constructor.

...