Java 不能使用另一个包中的公共方法 [英] Java can't use public method from one package in the another
问题描述
在同一个项目中,我有两个包,第一个包包含一个具有以下代码的类:
In the same project I have two packages, 1st package contains a class with this code:
package com.ginger;
public class SimplePrint
{
public SimplePrint(){}
public static void print(Object obj)
{
System.out.println(obj);
}
}
我想在另一个包的另一个类中使用 print()
方法,但在同一个项目中.
I would like use the method print()
in another class in another package, but within the same project.
import com.ginger.*;
public class MainClass
{
public static void main(String[] args)
{
print("Some");
}
}
但是编译器告诉我方法 print()
没有为第二个类定义.
But the compiler tells me that the method print()
is undefined for the 2nd class.
同时,我可以在第二个类中创建对象 SimplePrint s = new SimplePrint()
.
In the same time, I am able to create the object SimplePrint s = new SimplePrint()
in the 2nd class.
我是编程新手,如果我问的是简单的事情,请原谅.
I'm new to the programming, excuse me if i am asking about the simple thing.
推荐答案
有几种方法可以做到这一点:
There are a couple of ways to do this:
去掉print
方法的static
关键字,创建类的实例
Remove the static
keyword of the method print
and create an instance of the class
SimplePrint simplePrint = new SimplePrint();
就这样做
simplePrint.print("");
或者将上面的合并成一行:
Or combine the above into a single line:
new SimplePrint().print("");
静态
您保持 print
方法 static
并执行此操作
Static
You keep the print
method static
and just do this
SimplePrint.print("");
这篇关于Java 不能使用另一个包中的公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!