Java only creates sub class instance
Code example to show that when a new instance is created, Java only creates instance for the sub class, and for the super class.
package space.yuanjiang.java;
public class Test {
public static void main(String[] args) {
B obj = new B();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
class A {
int a = 111;
int b = 222;
}
class B extends A {
int c = 333;
int d = 444;
public B() {
System.out.println("this: " + this.hashCode());
System.out.println("super: " + super.hashCode());
System.out.println("class of this: " + this.getClass().getName());
System.out.println("class of super: " + super.getClass().getName());
}
}
/* output
this: 1846274136
super: 1846274136
class of this: space.yuanjiang.java.B
class of super: space.yuanjiang.java.B
111
222
333
444
*/