从不同的 JAVA 包调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35248947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:54:17  来源:igfitidea点击:

calling methods from different package JAVA

javapackages

提问by reddit_10

I have two packages; pack1 and pack2. in pack1 I have two classes the main called Prog and another one called ClassA. In pack2 I have one class called ClassB.

我有两个包裹;包1和包2。在 pack1 中,我有两个类,主要称为 Prog,另一个类称为 ClassA。在 pack2 中,我有一个名为 ClassB 的类。

I am trying to understand why I can't call a method from ClassB using the object. I can do that using the main class but not with another class.

我试图理解为什么我不能使用对象从 ClassB 调用方法。我可以使用主类来做到这一点,但不能使用另一个类。

Here's the code:

这是代码:

package pack1;
import pack2.ClassB;

public class Prog {
    public static void main(String[] args){

    }
}

Code for ClassA

A 类代码

package pack1;
import pack2.ClassB;

public class ClassA {
    ClassB o3 = new ClassB();
    // Error won't compile
    System.out.println(o3.getText());

}

Code for ClassB:

B类代码:

package pack2;

public class ClassB {
    final String TEXT = "This is a text";

    public String getText(){
        return TEXT;
    }
}

回答by Paul

The problem here isn't that you can't access the method. The problem is that statements must be enclosed either in a constructor, amethod-declaration or an initializer-block. So this would be valid code for example:

这里的问题不在于您无法访问该方法。问题是语句必须包含在构造函数、方法声明或初始化程序块中。所以这将是有效的代码,例如:

enter codepackage pack1;
import pack2.ClassB;

public class ClassA {
    ClassB o3 = new ClassB();

    public void someMethod(){
        System.out.println(o3.getText());
    }
}