Reputation: 17454
I am testing out various combinations to build a super class and a subclass and I realized there is no way to access the private fields from the parent class when I do the following:
abstract class Ball{
private int size;
protected Ball(int size){
this.size = size;
}
public abstract void setSize(int size);
public abstract int getSize();
}
class SoccerBall extends Ball
{
public SoccerBall(int size){
super(size);
}
@Override
public void setSize(int size){this.size = size;}//size not inherited
@Override
public int getSize(){return size;} //size not inherited
}
I know private fields won't be inherited to the subclass. The only way (probably the only way other than reflection) to access it is to use getter and setter.
So my questions:
(Q1) If I want to keep the field in the parent class as private and not protected. Should I not make the getter and setter abstract in order to make the private field accessible to its child?
(Q2) If I were to make the field (size) private, how should I implement my getter and setter to make the private field accessible by the subclasses?
Upvotes: 3
Views: 5065
Reputation: 17454
If I want to keep the field in the parent class as private and not protected. Should I not make the getter and setter abstract in order to make the private field accessible to its child?
Yes, since the field is private and can only be accessed if a getter and setter is defined in the parent class. The getter and setter should not be declared as abstract.
If I were to make the field (size) private, how should I implement my getter and setter to make the private field accessible by the subclasses?
Just implement a normal getter and setter in the parent class where the private field resides.
abstract class Ball{
private int size;
protected Ball(int size){
this.size = size;
}
protected void setSize(int size){
this.size = size;
}
protected int getSize(){
return size;
}
}
The subclass
class SoccerBall extends Ball{
public SoccerBall(int size){
super(size);
}
@Override
public void setSize(int size){
super.setSize(size);
}
@Override
public int getSize(){
return super.getSize();
}
}
Upvotes: 1
Reputation: 61
Instead of trying to access the value directly, change the access level of size to "protected". This way, it will will be mostly encapsulated except when accessed by subclasses.
Upvotes: 0