Java Covariants

后端 未结 7 844
臣服心动
臣服心动 2021-01-01 22:26
public class CovariantTest {
    public A getObj() {
        return new A();
    }

    public static void main(String[] args) {
        CovariantTest c = new SubCov         


        
7条回答
  •  半阙折子戏
    2021-01-01 23:05

    I was looking at your code and was having some trouble compiling it. Getting error

    The return type is incompatible with CovariantTest.getObj()

    I made a small change.

    class A {
        int x = 5;
    }
    
    class B extends A {
        int x = 6;
     }
    
    public class CovariantTest {
    
        public A getObj() {
            return new A();
        }
    
        public static void main(String[] args) {
            CovariantTest c = new SubCovariantTest();
            A a = c.getObj();
    
            System.out.println(c.getObj().x);
        }
    }
    
     class SubCovariantTest extends CovariantTest {
        public A getObj() {
            return new B();
        }
    
     }
    

    Stick a breakpoint in at the system out line and look at the a variable. It contains two x members, with one set to 5 and one to 6.

    Starblue's answer explains this behaviour.

提交回复
热议问题