How many objects are created due to inheritance in java?

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

    I am not sure how polymorphism/overriding works at the time of GC.

    But it should be worth a try to override finalize method in all your classes and check when JVM exits main method.

    • If only C object is created, it should call finalize for 'C'.
    • If all A,B, C object is created, it should call finalize for A,B, C.

    I think this is simplest check you can apply.

    class A {
        A() {
            //Super(); 
            System.out.println("class A");
        }
    
        public void finalize(){
        System.out.println("Class A object destroyed");
        }
    }
    class B extends A {
        B() {
           //Super(); 
            System.out.println("class B");
        }
    
        public void finalize(){
        System.out.println("Class B object destroyed");
        }
    }
    class C extends B {
        public static void main(String args[]) {
            C c = new C(); //Parent constructor will get call 
        }
    
        public void finalize(){
        System.out.println("Class C object destroyed");
        } 
    }
    

提交回复
热议问题