Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

generics - How covariant method overriding is implemented using bridging Technique in java

While reading on Covariant Overriding, i find out very strange fact,

covariant method overriding is implemented using a bridging technique. it also said that this feature is implemented in java5 and above.(i think it is because generics introduced from java5)

How it happens.Please help me with example.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Consider an example:

public interface Shape<T extends Shape<T>> {
    T getType();
    void setType(T type);
}

public class Circle implements Shape<Circle> {
    Circle getType() { }
    void setType(Circle circle) {  }
}

It looks good as of now. But, after type erasure, the interface loose it's generic type, and the type T is replaced with the upper bound. So the interface and class looks like:

public interface Shape {
    Shape getType();
    void setType(Shape type);
}

public class Circle implements Shape {
    Circle getType() { }
    void setType(Circle circle) {  }
}

Now, here's the problem. The method in Circle after erasure is not really an overridden version of Shape. Note that, now the methods as it looks, applies greater restriction on the parameter it takes, and the value it returns. This is because the erasure changes the signature of method in interface.

To solve this issue, the compiler adds bridge method for those, which delegates the call to those actual methods in class.

So, the class is really converted to:

public class Circle implements Shape {
    Circle getType() { }
    void setType(Circle circle) {  }

    // Bridge method added by compiler.
    Shape getType() { return getType(); }  // delegate to actual method
    void setType(Shape shape) { setType((Circle)shape); }  // delegate to actual method
}

So, the bridge method is now the overridden version of the methods in the interface, and they delegate the call to the actual method that does the task.

Note that the type used in the bridge method is the erasure of the type parameter of the interface, in this case Shape.


References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...