Thursday, February 10, 2011

Inheritence and Constructor

If a class has no constructor, javac will add a default no parameter constructor to it automatically when compile, and all
classes are derived from Object which has a default blank constructor.
When call the constructor of a class, it will call constructor of superclass first, except that it explicitly calls another
constructor using this(...) or super(...).
Let's run some sample code.
class A{
private int index = 11;
public A(){
System.out.println("A()");
}

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

public int getIndex(){
return index;
}
}

class B extends A{
private String name;
public B(){
// this("ramon");
System.out.println("B()");
}

public B(String name){
// super("ramon");
System.out.println("B(String)");
}
}

// check the test case
public class Main{

public static void main(String args[]){
B b = new B();
System.out.println("---------------");
B b1 = new B("ramon");
}
}

The output is:
A()
B()
---------------
A()
B(String)
You can see that every constructor of B will call A() first, now we apply a little change.
class A{
private int index = 11;
public A(){
System.out.println("A()");
}

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

public int getIndex(){
return index;
}
}

class B extends A{
private String name;
public B(){
this("ramon");
System.out.println("B()");
}

public B(String name){
// super("ramon");
System.out.println("B(String)");
}
}

// check the test case
public class Main{

public static void main(String args[]){
B b = new B();
System.out.println("---------------");
B b1 = new B("ramon");
}
}
The output is :
A()
B(String)
B()
---------------
A()
B(String)
Due to this("ramon") in B(), it will call B(String name) first, but B(String name) also need to call A() first(call default constructor
of superclass), finally the output is:
A()
B(String)
B()

Apply some more change:
class A{
private int index = 11;
public A(){
System.out.println("A()");
}

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

public int getIndex(){
return index;
}
}

class B extends A{
private String name;
public B(){
this("ramon");
System.out.println("B()");
}

public B(String name){
super("ramon");
System.out.println("B(String)");
}
}

// check the test case
public class Main{

public static void main(String args[]){
B b = new B();
System.out.println("---------------");
B b1 = new B("ramon");
}
}
The output is:
A(String)
B(String)
B()
---------------
A(String)
B(String)
This time B() will call B(String name) first, but B(String name) will call A(String name) first(due to super("ramon")).
From the example above, you should know the relationship between constructor and inheritence.

No comments: