How many objects are created due to inheritance in java?

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

    1. In your Case One object is created

    2. while doing the following, this super() will provided by Compiler Implicitly

      class A {
      A() {
          System.out.println("class A");
      }
      }
      class B extends A {
      B() {
          System.out.println("class B");
      }
      }
      class C extends B {
      public static void main(String args[]) {
          C c = new C(); //
      }
      }
      

    It is similar to calling a super() inside your methods

        B() {
            super();
            System.out.println("class B");
        }
    

    The super keyword can also be used when a method is overridden in the current class, but you want to invoke the super class method.

    super() will makes the all constructors reference to one class. (For easy understanding: Its like all the member functions are comes under a same class.) Its going to call all the constructor methods only.

    So its done the work of calling constructor only, so super() will not done any object creation. Its just referring the member functions.

提交回复
热议问题