Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

oop - Generic field polymorphism in Java

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fields aren't overridden in the way that methods are. If you want this kind of polymorphism, you have to do it with methods, not with fields.

Here, experienced and pro have two different fields named factor, one from AgeFactor, and one from experienced and pro. The fact that it has the same name is completely coincidental: if you have an object, and all that's known about it is that it's an AgeFactor, then the AgeFactor version of that field will be used.

A more sensible version of this design might be to have only one field named factor, and to set it in the constructors of each class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...