【问题标题】:Calling a public class inside a public class, from a different package从不同的包调用公共类中的公共类
【发布时间】:2014-10-05 03:27:08
【问题描述】:

这是我的问题:

我这样设置了 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) 没有 instacne

我能做些什么来防止这种情况发生?我知道如果我将所有类放在一个包中,它将被修复。但我认为这是一种愚蠢的解决方法。各位大佬有没有比较好的?

【问题讨论】:

    标签: java class package


    【解决方案1】:

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

    public InsideApple insideApple = new InsideApple();
    

    【讨论】:

      【解决方案2】:

      您不能在一个文件中声明多个公共类,也不能在另一个类中声明一个类,您的 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 变量应该是公共的,以便可以从其他类访问。​​

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-15
        • 2011-01-30
        • 1970-01-01
        • 2018-09-27
        • 2020-03-18
        • 1970-01-01
        相关资源
        最近更新 更多