user2509983
user2509983

Reputation: 101

Private fields accessible in subclasses

I have 2 classes

class A {
   private int count;
}

class B extends A {
   //need to access count here
}

What standard ways can I use to access it?

Upvotes: 0

Views: 482

Answers (4)

Tala
Tala

Reputation: 8928

you can declare your field as protected, then it will be accessible to all subclasses and package local classes.

you can also have getters/setters (general practice) if this field can be visible to everyone. Then you just call getCount() method to get count.

please refer here getters/setters example

Upvotes: 1

Raunak Agarwal
Raunak Agarwal

Reputation: 7228

Java prevents inheriting the private fields in to the sub-class. If you want to access the fields either you could use assessors i.e. getter methods or you could change the field access type to protected or public. Again, protected would only work if the sub-class file is in the same directory. If you have the files in separate directory you would need to change the field access type to Public

Upvotes: -1

Imre Kerr
Imre Kerr

Reputation: 2428

Either make count protected or add a getCount() method in A.

Upvotes: 7

stinepike
stinepike

Reputation: 54682

class A {
   private int count;

   public int getCount(){
       return count;
   }
}

class B extends A {
   //need to access count here
}

Upvotes: 0

Related Questions