Still trying to grasp Polymorphism and Inheritance
Let's say I have the following abstract class
Code:
abstract class Family {
private String name;
public void someMethod() {
//...Some code here to do stuff
}
}
And some classes that extends my abstract class:
Code:
public class Dad extends Family {
public Dad() {
}
public void methodA () {
//...code here to do stuff
}
}
Is it correct to have the Family class hold the String name since all subclasses of Family would have a String name variable? And if so, what is the best way to access that variable?
What I've tried that works:
Setting the variable String name as private and creating a protected method that the subclasses can use to access/set/get the variable.
Code:
abstract class Family {
private String name;
public void someMethod() {
//...Some code here to do stuff
}
protected void setName(String string) {
name = string;
}
}
public class Dad extends Family {
public Dad() {
}
public Dad(String string) {
setName(string);
}
public void methodA () {
//...code here to do stuff
}
}
Setting the String name as protected and directly accessing the variable within the subclass.
Code:
abstract class Family {
protected String name;
public void someMethod() {
//...Some code here to do stuff
}
}
public class Dad extends Family {
public Dad() {
}
public Dad(String string) {
name = string;
}
public void methodA () {
//...code here to do stuff
}
}
Which way is better... or is there an even better way?? Are there some guidelines to follow when designing abstract and subclasses that would be helpful??
Previous Post:
http://www.java-forums.org/new-java/...act-class.html