Java僅建立子類別實例

程式碼範例顯示,當建立新實例時,Java 僅為子類別和超類別建立實例。

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
 */

java