"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Member Access and Inheritance

Member Access and Inheritance

Published on 2024-11-03
Browse:653
  • 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 cannot access the members declared as private.

  • For example, if width and height are declared private in TwoDShape, the Triangle subclass cannot 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

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/acesso-a-membros-e-a-heranca-4pp2?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3