Confusing Java calling method

class Parent
{
    private void method1()
    {
        System.out.println("Parent method1()");
    }
    public void method2()
    {
        System.out.println("Parent method2()");
        method1();
    }
}

class Child extends Parent
{
    public void method1()
    {
        System.out.println("Child method1()");        
    }
}
class test {
    public static void main(String args[])
    {
        Parent p = new Child();
        p.method2();
    }
}

I got confused why in Parent :: method2 () when calling method1 () it will be cal Parents method1 (), and not Childs method1? I see that this only happens when method1 () is private? Can someone explain to me why? Thank you.

+3
source share
2 answers

This is based on scope rules; The Parentbest match for method1is the local private version of the class.

If you were to define method1as publicor protectedin Parentand override the method in Child, then the call method2would be instead Child method1.

+5
source

private , method1, Child, . javac , method1 . protected .

+5

All Articles