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?
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?
Either make count
protected
or add a getCount()
method in A
.
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
class A {
private int count;
public int getCount(){
return count;
}
}
class B extends A {
//need to access count here
}
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