When using the constructor method of a subclass to create an object of the subclass, not only the member variables declared in the subclass are allocated memory, but also the member variables of the parent class are allocated memory space, but only the part inherited by the subclass is allocated. Member variables serve as variables assigned to subclass objects.
That is to say, although the private member variables in the parent class have allocated memory space, they will not be used as variables of the subclass object; similarly, if the subclass and the parent class are not in the same package, although the friendly member variables of the parent class have allocated memory space , but not as a variable of a subclass object.
At this point, we more or less feel that some memory seems to be wasted when the subclass creates the object. This is because when an object is created with a subclass, the member variables of the parent class are also allocated memory space, but only part of it is used as variables assigned to the subclass object. For example: although the private member variables in the parent class have allocated memory space, they are not used as variables of the subclass object. Of course, they are not variables of an object of the parent class, because we do not use the parent class to create any objects at all. However, we should note that there are still some methods in the subclass that are inherited from the parent class, but these methods can operate on these uninherited variables.
For example: the object of the subclass ChinaPeople calls the inherited method to operate variables that are not inherited by the subclass but have allocated memory space.
classPeople{privateintaverHeight=168;publicintgetAverHeight(){returnaverHeight;}}classChinaPeopleextendsPeople{intheight;publicvoidsetHeight(inth){//height=h+averHeight;//Illegal, the subclass does not inherit averHeightheight=h;}publicintgetHeight(){returnheight; }}publicclassMainpublicstaticvoidmain(Stringargs[]){ChinaPeoplezhangSan=newChinaPeople();System.out.println(the value of averageHeight not inherited by the subclass object is: +zhangSan.getAverHeight());zhangSan.setHeight(180);System.out .println(The value of the instance variable height of the subclass object is: +zhangSan.getHeight());}}
The running results are as follows:
The value of averageHeight that is not inherited by the subclass object is: 168. The value of the instance variable height of the subclass object is: 180.