Home > Java > javaTutorial > Member Access and Inheritance

Member Access and Inheritance

WBOY
Release: 2024-09-10 06:40:02
Original
719 people have browsed it
  • 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.

Acesso a membros e a herança

  • 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.

Acesso a membros e a herança

Acesso a membros e a herança

The above is the detailed content of Member Access and Inheritance. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template