Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 886
Mario Mateaș Avatar asked Aug 30 '26 14:08

Mario Mateaș


2 Answers

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.

like image 120
Eran Avatar answered Sep 02 '26 05:09

Eran


At compile time A.greet() is not accessible.

Hence does not compile.

For overriding, the method must be accessible at compile time, but the decision to call the method is done at runtime.

like image 40
anantha ramu Avatar answered Sep 02 '26 05:09

anantha ramu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!