Method to establish a java subclass: first call the constructor in the parent class for initialization; then after the parent class is initialized, display the properties of the subclass and initialize it; finally perform specific initialization of the subclass constructor .
#The process of establishing a subclass: In Java's constructor, the first line will first call the constructor in the parent class for initialization. After the parent class is initialized, the properties of the subclass are then displayed and initialized. Perform specific initialization of subclass constructors. After initialization is completed, assign the address value to the reference variable Person p.
(Video tutorial recommendation: java course)
This article comes with an example of creating a subclass.
Person p = new Person();
1, JVM will read the Person.class file in the specified path and load it into memory, and will load Person's parent class first (if there is a direct parent class).
2, open up space in the heap memory and allocate addresses.
3, and in the object space, initialize the properties in the object by default.
4, call the corresponding constructor to initialize.
5, in the constructor, the first line will first call the constructor in the parent class for initialization.
6. After the parent class is initialized, the attributes of the subclass are displayed and initialized.
7, perform specific initialization of the subclass constructor.
8. After initialization, assign the address value to the reference variable Person p.
Example:
class Fu { Fu() { super(); show(); //通过结果可以看出,子父类有同名show方法,调用的是子类show方法。 return; } void show() { System.out.println("fu show"); } } class Zi extends Fu { int num = 8; Zi() { super(); //-->通过super初始化父类内容时,子类的成员变量并未显示初始化。等super()父类初始化完毕后, //才进行子类的成员变量显示初始化。 System.out.println("zi cons run...."+num); return; } void show() { System.out.println("zi show..."+num); } } class ExtendsDemo5 { public static void main(String[] args) { Zi z = new Zi(); z.show(); } }
The above is the detailed content of How to create a java subclass. For more information, please follow other related articles on the PHP Chinese website!