Hiding of Java member variables (example explanation)

1、 If there is a member variable with the same name in the subclass and the parent class, will the member variable of the subclass overwrite the member variable of the parent class? Let's look at the following example:

The result of running the main method of class C is:

10 20 10

From the results, we can see that the subclass will not overwrite the member variables of the parent class. Our eclipse debugging tool can also clearly see that there are two member variables of X in object a (one of which is the parent class), as shown in the following figure:

Through the results of the first and third, it can be concluded that direct access to members is statically bound. The official explanation is as follows:

In a class, if the member variables in the subclass have the same name as the member variables in the parent class, even if their types are different, as long as their names are the same. All member variables in the parent class are hidden.

In a subclass, the member variables of the parent class cannot be simply accessed by reference. Instead, you must obtain the hidden member variables of the parent class from the reference of the parent class. Generally speaking, we do not recommend hiding member variables,

Because it makes the code hard to read.

For static methods, it is similar to member variables, as follows:

The results are as follows:

A Static B Static A Static

The above article on hiding Java member variables (example explanation) is all the content shared by Xiaobian. I hope it can give you a reference and support programming tips.

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
分享
二维码
< <上一篇
下一篇>>