I have really got confused with Generics please help me with my situation:
public <M extends AgeFactor> void setAgeFActor(M m){
System.out.println("referene receiveed"+m.factor); //WHAT SHOULD IT REFER TO?? AgeFactor or type given at Runtime as young
this.factor=m.factor;
}
In the above code the reference M m
refers to AgeFactor
or the type that i give at Runtime.
Suppose i call it via:
ath1.setAgeFActor(new young()); //ath1 is referring to setAgeFActor method's class
and hierarchy being:
class AgeFactor {
String factor;
}
class young extends AgeFactor {
String factor = "Young";
public String toString() {
return " " + factor + " ";
}
}
class experienced extends AgeFactor {
String factor = "Experienced";
public String toString() {
return " " + factor + " ";
}
}
class pro extends AgeFactor {
String factor = "Pro";
public String toString() {
return " " + factor + " ";
}
}
What i want to know is why m.factor
refer to AgeFactor
's field factor
?? m.factor
should referring to young
or pro
the type i give at Runtime.
If m is actually referring to AgeFactor then i understand that m.factor will refer to AgeFactor's factor always because polymorphism is not applied to fields. If so, then what is the need of generics?
Are Java's generics generic itself?
Pleas help me getting over Generics.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…