What happens when a subclass does not define a constructor in Java?
I have a few things I want to know First, if you don't have a constructor:
class NoCons { int x; }
When I do the new nocons (), the default constructor is called What did it do? It sets x to 0, otherwise it will happen elsewhere?
What if I have this situation?
class NoCons2 extends NoCons { int y; }
What happens when I call the new nocons2()? Nocons2's default constructor is called, and then nocons2's constructor? Do they set their respective x and Y fields to 0?
What about this version
class Cons2 extends NoCons { int y; public Cons2() {} }
Now I have a constructor, but it doesn't call the constructor of the superclass How does x initialize? What if I have this situation?
class Cons { int x; public Cons() {} } class NoCons2 extends Cons { int y; }
Will the constructor be called?
I can try all these examples, but I don't know when to run the default constructor What is the general way to think about this so that I know what will happen in the future?
Solution
When the Java class does not explicitly define a constructor, a public no args default constructor is added:
class Cons { int x; }
amount to:
class Cons { int x; public Cons() {} }
The constructor of a subclass does not explicitly define the constructor of the parent class it calls. It will automatically call the default constructor of the parent class before the parent class So suppose:
class A { public A() { System.out.println("A"); } }
So this:
class B extends A { public B() { System.out.println("B"); } }
Fully equivalent to:
class B extends A { public B() { super(); System.out.println("B"); } }
And the output in both cases will be:
A B
So when you do:
new NoCons2();
The order is:
>Nocons's default constructor call, although this is technically the first part of (2); Next, the default constructor of > nocons2 is called