Slight confusion regarding overriding where variables are concerned

后端 未结 6 851
青春惊慌失措
青春惊慌失措 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:18

    Okay I know this is a bit late to reply to this question but I and my friend had the same problem and the answers already here didn't quite clear it for us. So I'll just state what problem I had and how it makes sense now :)

    Now I do understand that fields don't get overrided but instead they get hidden as miller.bartek pointed out and I also understand that overriding is for methods and not fields as Scott points out.

    The problem I had however was this. According to me,

    c1.getObject().x
    

    This must transform into:

    new B().x     // and not newA().x since getObject() gets overrided
    

    And that evaluates to 6.

    And I couldn't get why the variable of class A (super-class) is being called by an object of class B (sub-class) without having explicitly asked for such a behaviour.

    And guessing from the wording of the question, I feel the OP had the same question/doubt in mind.


    My Answer:

    You get a hint from Elbek's answer. Put the following lines in the main method and try to compile the code:

    A a = c1.getObject();    //line 1
    B b = c1.getObject();    //line 2
    

    You'll notice that line 1 is completely legal while line 2 gives compilation error.

    So when the function getObject() is being called, the CovariantTest (super) function IS getting overrided by SubCovariantTest (sub) function since that is valid overriding in the code and c1.getObject() WILL return new B().

    However, since the super-function returns a reference of class-type A, even after getting overrided, it must return a reference of class-type A unless ofcourse we type-cast it. And here, class B is a class A (due to inheritance).

    So practically, what we're getting from c1.getObject() is not

    new B()
    

    but this:

    (A) new B()
    

    That is why the output comes out to be 5 even though an object of class B is returned and class B has value of x as 6.

提交回复
热议问题