Reputation: 11
i am a 1st year IT Student taking OOP...
i have this abstract parent Class...
public abstract class Person{
private String Name;
protected Person(){
setName("xxxxxxxx");
}
public abstract String getName();
public abstract void setName(String name);
}
and this is its child class...
public class PetOwner extends Person{
private boolean hasKids;
private boolean hasAllergies;
public PetOwner(){
setName("xxxx");
setAllergies(true);
setKids(true);
}
public PetOwner(String name, boolean a, boolean k){
setName(name);
setKids(k);
setAllergies(a);
}
public String getName(){return Name;}
public void setName(String n){ Name = n;}
public boolean getAllergies(){return hasAllergies;}
public void setAllergies(boolean a){hasAllergies = a;}
public boolean getKids(){return hasKids;}
public boolean setKids(boolean k){hasKids = k;}
}
when i compile the child class it has errors that the "Name" is a private variable of Person.
my question is how can i access the private variables of the parent class in my child class by not changing it to public or protected??
Upvotes: 1
Views: 897
Reputation: 4078
public String getName(){return Name;} public void setName(String name){Name = name;}
public String getName(){return super.getName();} public void setName(String n){ super.setName(n);}
On Another Note: You're not assigning value to Name in your super class constructor. Write Name = xxxx instead because you are calling a setter that is abstract!
Upvotes: 2
Reputation: 36431
private
members are private to the entity they are defined in. protected
are private to the entity they are defined and to their subclasses. public
means no protection/accessible everywhere.
Roughly, if you define an attribute in a given entity then almost all the management of it should be defined at the same place. It means that if a Person
has a name
then the method setName
and getName
should be defined in Person
. They could be redefined in subclasses but they should at least be defined in Person
.
Think about it: why would you like (in common cases) every PetOwner
or ClergyMan
to define setName
? They will probably both do exactly the same; so factoring the definition in Person
is the right way.
Upvotes: 0