简体   繁体   中英

Accessing private method in Java

In java, a private access modifier is highly restrictive which can be accessed only within the class in which they are defined.

Consider the example.

    package x;
    public class Boom {

    protected String name;

    public Boom() {

    }

    private void aConfidentialInfo(){
        System.out.println("Some confidential information...");
    }

    protected void display(){
        System.out.println("In display method..");
        aConfidentialInfo();
    }

}

package y;
import x.Boom;

public class Hack extends Boom{

    public Hack{
        display();
    }   

}

Here when I run class Hack , it calls display followed by aConfidentialInfo which is a private member of class Boom . How is class Hack able to access the private member of class Boom ? Isn't it the infringement of private access modifier. How to understand and explain this with some decent reasoning?

No, it accesses a protected member of Boom- display. That's legal- a subclass or anything in the package can access a protected member. That protected function can access private members, because that protected function is part of the class Boom.

This is possible due to the magic of polymorphism.

Hack extends Boom and thus has access to all public, package, and protected fields and methods. It thus can call the protected display() method. With the magic of polymorphism, calling display in Hack calls Boom's method which is able to call aConfidentialINfo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM