简体   繁体   English

访问私有类中的私有方法

[英]Access to private methods in private class

How can I have access to a private method in a private class?如何访问私有类中的私有方法?

My code:我的代码:

public class OuterClass {

    private InnerClass ic;

    public OuterClass(){ //Constructor
        this.ic = new InnerClass();
    }

    public InnerClass getInnerClass(){
        return this.ic;
    }

    private class InnerClass {
        private VeryInnerClass vic;

        private void InnerClass(){
            this.vic = new VeryInnerClass();
        }

        private void method(Object item){
            //Job
        }

        private class VeryInnerClass {
            private Object item;

            private void VeryInnerClass(){
                //Constructor
            }

        }//End VeryInnerClass

    }//End InnerClass

}//End OuterClass

This is the main code:这是主要代码:

public class Main {

    public static void main(String[] args) {

        OuterClass oc = new OuterClass();
        Object item = new Object();

        oc.getInnerClass().method(item);

    }

}

The error is that the type OuterClass.InnerClass is not visible, but I used a getInnerClass() method, so I don't know how to have access to method(Object item) .错误是getInnerClass()类型不可见,但我使用了getInnerClass()方法,所以我不知道如何访问method(Object item)

No, you can't.不,你不能。

The private modifier specifies that the member can only be accessed in its own class private 修饰符指定该成员只能在它自己的类中访问

So, if you want to access to private methods, then you should define them with the public , protected or no modifier depending what is more appropriate in that case.因此,如果您想访问私有方法,那么您应该使用publicprotectedno 修饰符来定义它们,具体取决于哪种情况更合适。

See more in this doc在此文档中查看更多信息

您不能直接访问类范围之外的私有方法/私有内部类。

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

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