Adrian
Adrian

Reputation: 20068

Confusing calling method in 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.

Upvotes: 3

Views: 191

Answers (2)

Mark Elliot
Mark Elliot

Reputation: 77034

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.

Upvotes: 5

AdamH
AdamH

Reputation: 2201

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.

Upvotes: 5

Related Questions