Reputation: 529
if I have following inheritance relationship.
class product {
product(int param) {};
...
}
class parent {
private int secret;
...
parent() {
secret = 5; //for example; in real world it is set by complicated computation.
}
public create() {
return new product(secret);
}
}
now I need to extend parent class, as
class childProduct {
childProduct(int param) {};
...
}
class child extends parent {
child() {
super();
}
@Override
public public create() {
return new childProduct(secret);
}
}
Now it gets problem by secret is private so I cannot access it in child.
I resolved this problem by making secret protected.
class parent {
protected int secret;
However I think there is a elegant way to do it.
Anyone knows?
Thanks.
Upvotes: 0
Views: 31
Reputation: 24812
However I think there is a elegant way to do it. Anyone knows?
if you need to access a parent's member from a child implementation, then making that member protected IS the elegant way to do it.
Making a member private is to avoid sharing it with the world, including children. Making it protected is to avoid sharing it with the world, but share it with children (aka keep it in the family). Making it public, is to share it with the world.
You might expose the parent's member using a getter, either a protected getter or public, depending on how secret is your secret, and also on whether you want to decouple parent's members from child's members.
But accessing the parent's member by making it protected is just perfectly fine, and right, and elegant.
Upvotes: 3