Skip to content
Advertisement

Why doesn’t Java automatically access the overridden method?

Given two classes, a parent class and a child class:

class A {
    private void greet() {
        System.out.println("Class A");
    }
}

class B extends A {
    public void greet() {
        System.out.println("Class B");
    }
}

One has a method called greet(), which is private, and the other one defines a method with the same name, only that it is public. Now, as far as I know, the child’s greet() method doesn’t override the parent’s method, because it ‘hides’ it? (given the fact that private methods can’t be overridden?)

Now, given the following class and method (considered to be in the same package as A and B):

public class Main {
    public static void main(String[] args) {
        B b = new B();
        b.greet();
    }
}

This should compile. But this one:

public class Main {
    public static void main(String[] args) {
        A a = new B();
        b.greet();
    }
}

This one up here doesn’t compile, because it’s missing a typecast. My question would be: why? If the greet() method was public in both places, it would have shown Class B both times. I’m pretty confused about why Java doesn’t figure at runtime, for the second case, that a is actually referencing to an object of type B, and directly calls the method from class B.

Tried reading more about polymorphism in an OCA-preparation book, but the authors didn’t seem to be so specific about it.

Advertisement

Answer

In your snippet that doesn’t compile, the compiler sees that the compile time type of a is class A. Therefore, it will only allow you to call accessible methods of class A (or of super-classes of A). greet is a private method of A, and therefore not accessible. Therefore the compiler doesn’t allow calling it.

The fact that the runtime type of a would be class B, which has an accessible greet method, makes no difference, since the compiler doesn’t try to figure out what the runtime type of a variable would be.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement