Home >Java >javaTutorial >Member Access and Inheritance
In Java, instance variables of a class are often declared private to protect access and prevent tampering.
Inheritance does not invalidate the private access restriction.
Even if a subclass inherits all the members of its superclass, it will not be able to access the members declared as private.
For example, if width and height are declared private in TwoDShape, the Triangle subclass will not be able to access them.
The Triangle class will not compile because it tries to access width and height, which are private in TwoDShape, causing an access violation.
Private variables can only be accessed by members of the class in which they were declared; subclasses do not have access to these variables.
Although this may seem like a restriction, it is possible to work around the problem using accessor methods.
Accessor methods can be used to provide controlled access to private variables.
The following is an example of how to modify TwoDShape and Triangle to use accessor methods for width and height.
The above is the detailed content of Member Access and Inheritance. For more information, please follow other related articles on the PHP Chinese website!