简体   繁体   English

从不同的 package JAVA 调用方法

[英]calling methods from different package JAVA

I have two packages;我有两个包裹; pack1 and pack2.包 1 和包 2。 in pack1 I have two classes the main called Prog and another one called ClassA.在 pack1 中,我有两个类,一个叫做 Prog,另一个叫做 ClassA。 In pack2 I have one class called ClassB.在 pack2 中,我有一个名为 ClassB 的 class。

I am trying to understand why I can't call a method from ClassB using the object.我试图理解为什么我不能使用 object 从 ClassB 调用方法。 I can do that using the main class but not with another class.我可以使用主要的 class 做到这一点,但不能使用另一个 class。

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;
    }
}

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());
    }
}

//pack1 code here //这里打包1个代码

package pack1; package 包1;

import pack2.ClassB;导入pack2.ClassB;

class ClassA { class A类{

} }

public class Prog {公共 class 编{

public static void main(String[] args) {
// write your code here
    ClassB o3 = new ClassB();
    // Error won't compile
    System.out.println(o3.getText());


}

} }

//pack2 code here

package pack2; package 包2;

public class ClassB { final String TEXT = "This is a text"; public class ClassB { final String TEXT = "这是一个文本";

public String getText() {
    return TEXT;
}

}[You don't need to create classA you can directly import pack2 and its class,method] }[不需要创建classA可以直接导入pack2及其class,方法]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM