How many objects are created due to inheritance in java?

前端 未结 14 1659
长情又很酷
长情又很酷 2020-11-29 18:48

Let\'s say I have three classes:

class A {
    A() {
        // super(); 
        System.out.println(\"class A\");
    }
}
class B extends A {
    B() {
             


        
14条回答
  •  醉话见心
    2020-11-29 19:43

    If you add one more line of Code System.out.println(this.hashCode()) will remove your confusion.

    Here in All Case hashCode() will print same hashCode all the time. It means there is one and only one unique Object is Created.

    class A {
        A() {
            // super(); 
            System.out.println(this.hashCode()); // it will print 2430287
            System.out.println("class A");
        }
    }
    class B extends A {
        B() {
            // super(); 
            System.out.println(this.hashCode()); // it will print 2430287
            System.out.println("class B");
        }
    }
    class C extends B {
        public static void main(String args[]) {
            C c = new C(); //Parent constructor will get called
            System.out.println(this.hashCode()); // it will print 2430287
        }
    }
    

    but there is two Constructor is getting invoked to initialize the Parent member variable. I think if you know the concept of super() keyword which invokes the Constructor of parent Class and Initialize the member Variable of parent Class.

提交回复
热议问题