srk
srk

Reputation: 5156

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?

Upvotes: 2

Views: 256

Answers (2)

Gabe Sechan
Gabe Sechan

Reputation: 93728

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.

Upvotes: 5

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

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()

Upvotes: 3

Related Questions