2014-10-04 117 views
0

这里是我的问题:调用公共类中的公共类,从不同的包

我设置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)是一个公共类内部类(苹果) 当我尝试从类调用类(InsideApple)内的方法(橙色),我没有问题。 但是,当我尝试从类(金枪鱼)它做到这一点时,它说类(苹果)内没有instacne类(InsideApple)

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

回答

1

你要做的从改变默认insideApple的知名度,公众

public InsideApple insideApple = new InsideApple(); 
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变量应该是公开的,以便可以从其他类访问它。