-2

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;}
}
ildun
  • 1
  • 1
  • Because aTest calls method of Test class and aChild calls method of Child class, this is cold compile time binding and run time binding. (or static binding and dynamic binding) do read some polymorphism in java and you will undesrstand more, or google dynamic and static binding – George Weekson Oct 25 '20 at 18:30
  • You can't make a private method in a superclass public in a subclass, the only reason your code works at all is because main is declared inside Test so you can access the private method – Joakim Danielson Oct 25 '20 at 18:30
  • yeap and it is not even ovverriden. just noticed. nice catch Joakim – George Weekson Oct 25 '20 at 18:33

1 Answers1

-2

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

Jay
  • 1,539
  • 1
  • 16
  • 27