Slight confusion regarding overriding where variables are concerned

后端 未结 6 853
青春惊慌失措
青春惊慌失措 2020-11-28 11:40

I\'m preparing for the SCJP (recently rebranded as OCPJP by Oracle) and one particular question that I got wrong on a mock exam has confused me, the answer description doesn

6条回答
  •  没有蜡笔的小新
    2020-11-28 12:04

    You are calling method from c1: System.out.println(c1.getObject().x);

    c1 reference type is:

    public class CovariantTest 
    {
        public A getObject() 
        {
           return new A();
        } 
        public static void main(String[]args) 
        {
           CovariantTest c1 = new SubCovariantTest();
           System.out.println(c1.getObject().x);
        }
    }
    

    so for this: c1.getObject() return type is A. from A you getting directly attribute not method, as you mention java does not override attributes, so it is grabbing x from A

提交回复
热议问题