这是我的问题:

我像这样设置了4个类(所有公共类):

Package main
--Class Tuna
Package second
--Class Apple
----Class InsideApple
--Class Orange


每个代码:

public class Tuna {

    public static void main(String[] args){
        Orange orange = new Orange();
        orange.callApple();

        Apple apple = new Apple();

        System.out.println("A call from orange");
        apple.callApple();
        apple.insideApple.callInsideApple(); // This line will crash it -- Why?
    }
}




public class Apple{

        public void callApple(){
            System.out.println("Here is Apple!");
        }

        InsideApple insideApple = new InsideApple();

        public class InsideApple{

            public void callInsideApple(){
                System.out.println("Here is Inside Apple!");
            }

        }

    }




public class Orange{

    Apple apple = new Apple();

    public void callApple(){
        System.out.println("A call from orange");
        apple.callApple();
        apple.insideApple.callInsideApple();
    }

}


如您所见,第4类(InsideApple)是内部类(Apple)的公共类
当我尝试从类(橙色)调用类(InsideApple)内部的方法时,我没有遇到任何问题。
但是,当我尝试从班级(Tuna)上做时,它说班级(Apple)内没有班级(InsideApple)的即时状态

我该怎么做才能防止这种情况?我知道如果将所有类都放在一个包中将得到修复。但是,我认为这是一种愚蠢的解决方法。你们有更好的骑手吗?

最佳答案

您必须将InsideApple的可见性从默认更改为公开

public InsideApple insideApple = new InsideApple();

09-27 06:45