user7275827
user7275827

Reputation:

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

Upvotes: 1

Views: 10303

Answers (2)

Lew Bloch
Lew Bloch

Reputation: 3433

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.

Upvotes: 0

peval27
peval27

Reputation: 1309

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.

Upvotes: 1

Related Questions