3
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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

for his example, may as well add friendly to the list.
i guess he ment friend :) Thanks for explination Mark Elliot
Friendly refers to the absence of a public/protected/private designator. Friendly methods are accessible by any class in the same package. Friends, that is what I meant. :)
friend concept is in c++ not in java. In java no-modifier or default modifier. These default modifiers are confusing to detect by reflection and hence i dont like them too much, anyway its out of context here.
5

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.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.