I am facing one confusion.
Here is my small code snippet
public class Father {
public String x;
public Father() {
this.init();
System.out.println(this);
System.out.println(this.x);
}
protected void init() {
x = "Father";
}
@Override
public String toString() {
return "I'm Father";
}
void ParentclassMethod(){
System.out.println("Parent Class");
}
}
public class Son extends Father {
public String x;
@Override
protected void init() {
System.out.println("Init Called");
x = "Son";
}
@Override
public String toString() {
return "I'm Son";
}
@Override
void ParentclassMethod(){
super.ParentclassMethod();
System.out.println("Child Class");
}
}
public class MainCLass{
public static void main(String[] args){
Son ob = new Son();
}
So when I'm creating a Son's class instance which is inherited from Class Father, so JVM automatically calls Father's class constructor. It creates Son type instance when Father's constructor called otherwise Father's fields wont initialized. So far Good..!
As you can see field x
is derived from Father's class into Son's class.
And my code initializing x
using init()
method.
Then why its showing null.
Its very confusing. Can any one explain ?