How many objects are created due to inheritance in java?

前端 未结 14 1655
长情又很酷
长情又很酷 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:44

    In Code only one object will be created and super call the parent class constructor .

    Prove of object creation :

    package one;
    
    public class A {
        public static A super_var;
    
        public A() {
            super_var = this;
            System.out.println("Constrcutor of A invoked");
        }
    }
    
    package two;
    
    public class B extends A {
        public static A sub_var;
    
        public B() {
            sub_var = this;
            System.out.println("Constructor of B invoked");
        }
    
        public void confirm() {
            if (sub_var == A.super_var)
                System.out.println("There is only one object is created");
            else
                System.out.println("There are more than one object created");
        }
    
        public static void main(String Args[]) {
            B x = new B();
            x.confirm();
        }
    }
    

    This will prove that there will be only one object created.

    And about Super(). What I know that it call Parent class constructor . and each constructor ahve Super() as first statement like you mention in your code . so that you know

    I don't know how it internally call super class constructor .

    Hope this will make you understand there is only the instace you create in program

提交回复
热议问题