The state of the derived class object is called when the Base class constructor calls the covering method in Java.

Please refer to the following java code:

class Base{
     Base(){
         System.out.println("Base Constructor");
         method();
     }
     void method(){}    
}

class Derived extends Base{
    int var = 2;
    Derived(){
         System.out.println("Derived Constructor");  
    }

     @Override
     void method(){
        System.out.println("var = "+var);
     }
 }

class Test2{
    public static void main(String[] args) {
        Derived b = new Derived();
    }
}

The output you see is:

Base Constructor
var = 0
Derived Constructor

I think var = 0 because the derived object is half initialized; Similar to Jon skeet says here

My question is:

If the derived class object is not created, why is the overriding method called?

When is var assigned to 0?

Are there any use cases that require this behavior?

Solution

>Derived object created - only constructor has not been run After the immediate is created, the type of the object will not change until all constructors run

Several criteria:

>Try not to do a lot of work in constructors One way to avoid this is to work with static methods, and then make the last part of the static method a constructor call that simply sets the field Of course, this means that you won't get the benefit of polymorphism when doing this work - but it's dangerous to do so in constructor calls. > Try to work very hard to avoid calling non - Final methods during constructors - this is likely to cause confusion Record any method calls that you really want to do very clearly so that anyone can override them. They all know to call them before initialization is completed. > If the method is to be invoked in the construction process, it is usually inappropriate to call it later. If this is the case, record it and try to name it. > Try not to overuse inheritance - this only becomes a problem when you subclass from a superclass other than object:) designing inheritance is tricky

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>