问题
Consider a Superclass A and a derived class B whereas A contains a private variable x
. B contains an explicit super() call as first argument inside its constructor while there might be some other variables of B like y
and z
. As far as I know there is no inheritance for private fields. Does that mean private fields will not get instantiated while executing:
B b = new b();
My question is: How does the heap look like after running the above code? Of course there will be y
and z
, but what about x
in this case?
回答1:
Field inheritance and field visibility are two separate concepts, not to be confused.
Field inheritance
In a way (to simplify a bit), a class is a template from making objects. So if a class A
declares two fields f1
and f2
, then instantiating A
creates objects (and allocates memory for them on the heap) that have these two fields.
A subclass is also a template for making objects, but this template is expressed as an addition to another class. So if class B
declares field f3
and extends A
, it's basically saying, "take all the fields that A
defines, and add f3
". So instantiating B
results in an object with three fields f1
, f2
, f3
.
Field Visibility
Field visibility, as expressed through access modifiers like private
and public
, is a way to control which part of the code "sees" (or can refer to) a certain field. The private
modifier means that no code outside of the class that declares the field can refer to this field. However, it doesn't mean that the field stops existing. To make a dodgy parallel, if you and another person are in a room and you turn off the light, you can't see the other person, but they are still there.
To emphasize the point that the concepts are separate, consider that in some cases you can see fields that are not inherited (e.g., because they are non-private, but in a class not in the same class hierarchy). And in some cases you can't see fields that are inherited, as in the case of private fields in the superclass.
回答2:
The private field defined in the super class is instantiated when a statement does that.
The fact that you manipulate a subclass doesn't change anything on this point. The field is always existing and instantiable, just the subclass cannot access it directly.
If the field of the super class was not instantiable, the Java inheritance would make not any sense since the subclasses would be not consistent or even unusable as superclass methods will not work any longer.
For example :
private int x;
A(){
this.x = getIntValue();
}
int getX(){return x;}
And B the subclass :
B(int x){
super(); // in the compiled code even if not in the source code
}
new B().getX()
will of course return the value of x instantiated in the superclass.
来源:https://stackoverflow.com/questions/56995922/are-private-fields-of-superclass-getting-a-place-inside-heap-memory-too-during