简体   繁体   English

在Java中访问私有方法

[英]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. 在java中,私有访问修饰符具有高度限制性,只能在定义它们的类中访问。

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 . 在这里,当我运行类Hack ,它调用display,然后调用aConfidentialInfo ,它是Boom类的私有成员。 How is class Hack able to access the private member of class Boom ? Hack类如何能够访问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. 不,它访问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. 受保护的函数可以访问私有成员,因为受保护的函数是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. Hack 扩展了 Boom,因此可以访问所有公共,包和受保护的字段和方法。 It thus can call the protected display() method. 因此它可以调用受保护的display()方法。 With the magic of polymorphism, calling display in Hack calls Boom's method which is able to call aConfidentialINfo() 借助多态的魔力,在Hack中调用display会调用Boom的方法,该方法可以调用aConfidentialINfo()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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