How covariant method overriding is implemented using bridging Technique in java

后端 未结 3 846
执念已碎
执念已碎 2020-12-18 04:26

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

covariant method overriding is implemented using a bridging technique. it also

3条回答
  •  旧时难觅i
    2020-12-18 05:18

    Given the following two classes:

    public class Node {
        private T data;
        public Node(T data) { this.data = data; }
    
        public void setData(T data) {
            System.out.println("Node.setData");
            this.data = data;
        }
    }
    
    public class MyNode extends Node {
        public MyNode(Integer data) {
     super(data); }
        public void setData(Integer data) {
            System.out.println("MyNode.setData");
            super.setData(data);
        }
    }
    

    When compiling a class or interface that extends a parameterized class or implements a parameterized interface, the compiler may need to create a synthetic method, called a bridge method, as part of the type erasure process.

    To solve this problem and preserve the polymorphism of generic types after type erasure, a Java compiler generates a bridge method to ensure that subtyping works as expected. For the MyNode class, the compiler generates the following bridge method for setData:

    class MyNode extends Node {
    
        // Bridge method generated by the compiler
        //
        public void setData(Object data) {
            setData((Integer) data);
        }
    
        public void setData(Integer data) {
            System.out.println("MyNode.setData");
            super.setData(data);
        }
    
        // ...
    }
    

提交回复
热议问题