简体   繁体   中英

How to get attributes of a parent class in Java?

How do I get the attributes of Class A, a parent class (super class), to use it in Class C in Java.

For instance:

Class B extends A

Class C extends B

You need to declare the member protected:

public class A
{
    protected int myInt = 5;
}

public class B extends A
{
}

public class C extends B
{
   public int GetInt()
   {
     return myInt;
   }
}

private member can be accessed only by the class itself, protected by the class and all the derived classes.

Typically it is best to keep attributes private, and access them via accessor (getter) and mutator (setter) methods from any other class, including derived classes. If the variable must or should be accessed directly from subclasses, which occasionally is desirable but not usually, then nearly always declare it protected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM