Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why could base class method call a non-exist method?

class BaseClass {
    private void f() {
        System.out.println("Baseclass f()");
    }

    public static void main(String[] args) {
        BaseClass dc = new DerivedClass();
        dc.f();
    }
}

class DerivedClass extends BaseClass {
    public void f() {
        System.out.println("DerivedClass f()");
    }
}

In my opinion, the object dc refers to should have only one non-override method - public void f() method,which make it(the public method) invisible when refered to with BaseClass reference.Since the object dc referes to does not have the private void f() method either because the DeriverClass could not inherit the private method,how could the object dc refers to call method f()?

thanks.

like image 629
Jichao Avatar asked Nov 21 '25 08:11

Jichao


1 Answers

A common(ish) misconception is that private is per instance rather than per class.

For example:

class Foo
{
    private int a;

    public bar(final Foo other)
    {
        other.a = 5;
    }
}

Some people are under the impression that the code above should not work because "a" is "private". That is not the case, any Foo instance can access the private variables/methods of any other Foo instance. "private" just means that instances of other classes (other than Foo in this case) cannot access the private members.

like image 58
TofuBeer Avatar answered Nov 23 '25 22:11

TofuBeer



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!