How many objects are created due to inheritance in java?

前端 未结 14 1624
长情又很酷
长情又很酷 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");
        } 
    }
    
    0 讨论(0)
  • 2020-11-29 19:50

    I agree with the previously posted answers, but want to add a reference to the ultimate authority on this issue, the Java Language Specification.

    The expression new C() is a "Class Instance Creation Expression". Section 15.9.4 Run-time Evaluation of Class Instance Creation Expressions describes the run time steps involved in creating an object. Note that it refers to "the object", and only allocates space once, but states "Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type."

    This all becomes much clearer by distinguishing between creating a new object, and invoking a constructor. Invoking a constructor only does part of object creation, the part that runs initializers, superclass constructors, and the body of the constructor. Because a C is also a B, the B constructor has to run during creation of a C.

    0 讨论(0)
提交回复
热议问题