Java Covariants

后端 未结 7 848
臣服心动
臣服心动 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 22:52

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

    Simple... Polymorphism is only applicable for functions. Not variables.

    Variables will be resolved during compile time.

提交回复
热议问题