When a subclass calls a parent class attribute, the access rights determine the specific method: the subclass can directly access public attributes. Protected properties can be accessed by inheriting the parent class or being in the same package as the parent class. Private properties cannot be accessed directly and must be accessed through the getter and setter methods of the parent class.
In Java, a subclass calls the properties of the parent class
In Java, a subclass can access the properties of the parent class , but the exact method depends on the access rights of the property.
1. Public properties
Subclass object. Parent class public attributes
2. Protected attributes
Subclasses can access the protected attributes of the parent class in the following ways:
Subclass object. Parent class protected attribute
Example:
<code class="java">class Parent { protected int age; } class Child extends Parent { public void printAge() { System.out.println("Age: " + age); } }</code>
3. Private properties
Subclass object.get parent class private property()
or Subclass object.set parent class private property()
Example:
<code class="java">class Parent { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Child extends Parent { public void printName() { System.out.println("Name: " + getName()); } }</code>
The above is the detailed content of How to call parent class attributes in java. For more information, please follow other related articles on the PHP Chinese website!