1
public class Test1{
    String name = "Test1";
    String getName(){
        return name;
    }
}
public class Test2 extends Test1{
    String name = "Test2";  
}
public class Test {
    public static void main(String[] args) {
        Test2 t = new Test2();
        System.out.println(t.getName());
    }
}

Why t.getName() returns "Test1". If that's the case, getName() cannot be inherited properly because the inheritance method getName() will always trace the name in super class, which is not applicable. Am I right?

  • You're not overriding the method. – fabian Jun 09 '14 at 05:02
  • 1
    My guess is that because `name` in `Test2` *hides* `name` in `Test1`, as fields aren't polymorphic. So inheritance is working as expected. I'm just not too sure exactly how namespaces here are resolved... – awksp Jun 09 '14 at 05:02
  • 1
    You are not overriding the method `getName()` so when u called the method it returns the super class variable to get result `TEST2` you must override the `getName()` method in TEST2 class. – amit bhardwaj Jun 09 '14 at 05:15

0 Answers0