Home > Java > javaTutorial > How to call parent class attributes in java

How to call parent class attributes in java

下次还敢
Release: 2024-04-26 22:48:15
Original
1192 people have browsed it

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.

How to call parent class attributes in java

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

  • Subclasses can directly access the public properties of the parent class.
  • Syntax: Subclass object. Parent class public attributes

2. Protected attributes

  • Subclasses can access the protected attributes of the parent class in the following ways:

    • The subclass inherits the parent class.
    • The subclass and the parent class are in the same package.
  • Syntax: 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>
Copy after login

3. Private properties

  • Subclasses cannot directly access the private properties of the parent class.
  • You need to access private properties through the getter and setter methods of the parent class.
  • Syntax: 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>
Copy after login

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template