Reputation: 65
I understand that private variables aren't inherited, so how can I gain access to it in my subclass?
i.e
class A{
private int i = 5;
// more code
}
class B extends A{
public int toInt(){
return super.i;
}
}
Upvotes: 1
Views: 148
Reputation: 115328
Generally you can't and should not. This is the reason that the variable is private
.
If you want to implement your base class to allow its subclasses to get access to the private members implement protected
accessor methods (either getters or setters). You can also mark the fields as protected
but I do not recommend even to start with it. You need very serious reason to make non-private fields.
The "workaround" that is possible in java is using reflection API:
Field f = A.class.getDeclaredField("i");
f.setAccessible(true);
f.get();
Upvotes: 3
Reputation: 234655
Normally you'd mark i
as protected
which allows sub-classes to see the field.
Another approach is to write a get
-style function, which sometimes can be better especially if you want to disallow sub-classes from writing to the field. Writing a put
-style function really defeats encapsulation.
Reflection also offers another way of circumventing private
, but using that approach is not to be recommended.
Upvotes: 5