Reputation: 101
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: 483
Reputation: 8938
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
Reputation: 7238
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
Reputation: 54742
class A {
private int count;
public int getCount(){
return count;
}
}
class B extends A {
//need to access count here
}
Upvotes: 0