从另一个包中调用公共类中的公共类

时间:2014-10-04 19:13:10

标签: java class package

这是我的问题:

我设置了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) 当我尝试从类(Orange)中调用类(InsideApple)中的方法时,我没有遇到任何问题。 但是,当我尝试从课堂(金枪鱼)做到这一点时,它说类(Apple)中没有类(InsideApple)的instacne

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

2 个答案:

答案 0 :(得分:1)

您必须将insideApple的可见性从默认值更改为公共

public InsideApple insideApple = new InsideApple();

答案 1 :(得分:0)

您不能在一个文件中声明多个公共类,也不能在另一个类中声明一个类,您的Apple.java文件应该类似于以下内容:

public class Apple{

    public InsideApple insideApple = new InsideApple();

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

} 
class InsideApple{

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

}

另外,正如您所看到的,insideApple变量应该是公共的,以便可以从其他类访问它。