I have tried to implement what you are asking with HAS-A
relationship and runtime polymorphism.
In below example, Age
is a parent class containing more generalized properties for all age groups.
Different age groups are divided in several class. Those classes contains age specific code or properties and will extend Age
class. For example Young
and Elder
class.
class Age {
// Generalized code for Age class
}
class Young extends Age {
// more specific code of Young class
}
class Elder extends Age {
// Elder class specific code
}
public class test {
Age age ;
int ageValue ;
public Age returnVal(int ageValue){
if (ageValue < 20) {
age = new Young();
} else {
age = new Elder();
}
// age object you get will be according to ageValue.
return age;
}
}
returnVal()
method will return you the object of either Young
class or Elder
class according to ageValue
.