Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing calling method in Java

Tags:

java

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

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

I'm confuse why does in Parent::method2() when invoking method1() it will cal Parents method1() and not Childs method1 ? I see that this happens only when method1() is private? Can someone explain me why ?
Thanks you.

like image 955
Adrian Avatar asked Dec 15 '25 12:12

Adrian


2 Answers

This happens based on scoping rules; in Parent the best match for method1 is the class-local private version.

If you were to define method1 as public or protected in Parent and override the method in Child, then calling method2 would invoke Child's method1 instead.

like image 66
Mark Elliot Avatar answered Dec 17 '25 03:12

Mark Elliot


private methods can't be overriden, hence the method1 you specify on Child isn't linked. javac assumes you must mean the method1 on the parent. Changing it to protected will work.

like image 30
Melv Avatar answered Dec 17 '25 01:12

Melv