Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private method can be accessed outside class in java

Tags:

java

i have tried the following code in net beans i am expecting error but i didn't get any error

class B {

    private void method() {
    }

    public static void main() {
        B b = new B();
        B c = new C();
        b.method();
        c.method();
    }
}

class C extends B {
}

When c.method() tries to access the method it should show error but in NetBeans it is not showing. Please tell me what is the fault.

like image 931
hemanth Avatar asked Feb 07 '26 00:02

hemanth


1 Answers

The way you have your method defined, you are calling C.method() from inside B.main(). Since method is private to B, the method is visible inside of B.main() even though the object is of type C which inherits from B.

like image 69
Justin Niessner Avatar answered Feb 08 '26 13:02

Justin Niessner



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!