Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when subclasses don't define a constructor in Java?

Tags:

java

oop

generics

I have a few cases I wonder about. First, if you have no constructor:

class NoCons { int x; }

When I do new NoCons(), the default constructor gets called. What does it do exactly? Does it set x to 0, or does that happen elsewhere?

What if I have this situation:

class NoCons2 extends NoCons { int y; }

What happens when I call new NoCons2()? Does NoCons's default constructor get called, and then NoCons2's constructor? Do they each set the 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 super class's constructor. How does x ever get initialized? What if I had this situation:

class Cons { int x; public Cons() {} }
class NoCons2 extends Cons { int y;  }

Will the Cons constructor be called?

I could just try all these examples, but I can't tell when a default constructor is run. What's a general way to think about this so that I'll know what happens in future situations?

like image 573
Claudiu Avatar asked Dec 10 '09 03:12

Claudiu


1 Answers

When a Java class has no constructor explicitly defined a public no-args default constructor is added so:

class Cons { int x; } 

is equivalent to:

class Cons { int x; public Cons() {} }

A subclass's constructor that doesn't explicitly define which of its parent's constructor it calls will automatically call the default constructor in the parent class before it does anything else. So assuming:

class A { public A() { System.out.println("A"); } }

then this:

class B extends A { public B() { System.out.println("B"); } }

is exactly 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:

  1. NoCons's default constructor called, although this is technically the first part of (2); and then
  2. NoCons2's default constructor called.
like image 89
cletus Avatar answered Oct 07 '22 19:10

cletus