Initialized in the parent class inherits Java programming ideas [reading notes]

Inherited initialized in the parent class

p144 Page Impressions

First, the problem

Suppose there are a number of classes that have inheritance when initialized when a subclass object, the parent of this class is concerned, what happened then? I am just copy a reference or a new parent will also objects?

Second, explain the problem

As it relates to the relationship between parent and child classes, from the outside, it appears that the parent class has a subclass of the same interface, and may contain some additional methods and fields. But inherit not just simply copy interface trouble parent class. When you create a sub-class of objects, it contains a parent class "of the
elephant." This object as if it were an object we created based on the parent class itself. From the outside, the object of the encapsulated parent class to the object in the subclass. Of course, the parent object should be initialized correctly, but only one way to ensure this: perform the initialization in the builder, a builder by calling the parent class, which has sufficient capacity and authority to perform the initialization of the parent class. In a subclass of Builder, Java automatically inserts calls to the parent class's building.

Third, the verification problem

class Art {
 Art() {
 System.out.println("Art 构造器");
 }
}


class Drawing extends Art {
 Drawing() {
 System.out.println("Drawing 构造器");
 }
}


public class Cartoon extends Drawing {
 Cartoon() {
 System.out.println("Cartoon 构造器");
 }
 public static void main(String[] args) {
 Cartoon x = new Cartoon();
     }
} 

Output:

Art 构造器
Drawing 构造器
Cartoon 构造器

As can be seen, is constructed on the basis of the class "external" performed, so the base class in the derived class accesses it be initialized before.
Even without creating a builder for the Cartoon (), the compiler will automatically synthesize a default for our builder, and issue to build the base-class
caller, and the order is from the most grandpa class - in this order subclass - superclass carried out, corresponds to the initialization sequence based on an article.

Guess you like

Origin www.cnblogs.com/blackmlik/p/12360215.html