Slight confusion regarding overriding where variables are concerned

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

    The technical term for what is happening here is "hiding". Variables names in Java are resolved by the reference type, not the object they are referencing.

    • A object has a A.x variable.
    • B object has both A.x and B.x variables.

    However instance methods with the same signature are "overridden" not "hidden", and you cannot access the version of a method that is overridden from the outside.

    Note that hiding also applies to static methods with the same signature.

    Your mock question in a simplified form (without overriding):

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

提交回复
热议问题