Search code examples
javapolymorphismoverriding

Why isn't this method overridden?


Why are the values 2 and 10 in the output? Isn't myMethod method overridden? Yes, if I change the access modifier of the method in the Test class from private to any other, the output will be as I expected it - 2 and 20. But I thought that the method of the child class should be at least as accessible as the method of the parent class - this is the only condition (related to access modifiers) to override the method.

public class Test {
    private int myMethod(int x){return x;}
    public static void main(String[] args) {
        Test aTest = new Test();
        Test aChild = new Child();
        System.out.println(aTest.myMethod(2));
        System.out.println(aChild.myMethod(10));
    }
}
class Child extends Test{
    public int myMethod(int x){return 2*x;}
}

Solution

  • Because myMethod in Test is private and Child class doesn't see it.