[英]Why can't I call this function in Java?
import static com.example.hello.Tools.*;
public class MAINCLASS{
public void run(){
runtools(); // this works
}
private class People{
public void runpeople(){
runtools(); // this does not work.
}
}
}
Inside Tools... 内部工具...
Edit: When I roll over runtools() in People.runpeople()...I get this: 编辑:当我在People.runpeople()中将runtools()滑过时,我得到以下信息:
The method runtools() is undefined for the type MAINCLASS.People 对于类型MAINCLASS.People,未定义方法runtools()
public class Tools {
public void runtools() {
....
}
}
Does anyone know why? 有人知道为什么吗?
You need to declare Tools#runtools()
static
to be able to import static
it. 您需要将
Tools#runtools()
声明为static
才能将其import static
。
public class Tools {
public static void runtools() {
// ...
}
}
Either that, or instantiate Tools
and then call runtools()
on it. 要么实例化
Tools
,然后对其调用runtools()
。
new Tools().runtools();
In reference to another question you asked recently related to this same class and it's issues: Why can't I put my functions in another class? 关于您最近提出的与此同一个类有关的另一个问题,它的问题是: 为什么我不能将函数放在另一个类中?
Does taking cletus' suggestion of removing the 'static' from the import call fix this issue as well? 是否采用cletus的建议从导入调用中删除“静态”,是否也解决了此问题? The 'static' bit is still there.
“静态”位仍然存在。
在这两种情况下,对runtools()
的调用runtools()
不起作用,因为runtools不是静态方法-它需要调用Tools
对象的实例。
That code shouldn't work (at all) as you posted it because you only import static members of Tools, and runtools() is an instance method. 该代码在发布时根本不起作用,因为您仅导入了Tools的静态成员,而runtools()是一个实例方法。 If you were to make runtools() static, then both invocations of runtools() should work because it is in scope in both cases.
如果要将runtools()设为静态,则runtools()的两个调用都应该起作用,因为这两种情况都在范围内。
This does not compile. 这不会编译。 You cannot import a package, with the static keyword.
您不能使用static关键字导入软件包。 The import needs to be a specific method.
导入需要是一种特定的方法。
So you need to write something like this to make it compile, and work: 因此,您需要编写类似这样的内容以使其编译并工作:
import static com.example.hello.Tools.someMethod;
Also, the method you're importing needs to be static. 另外,您要导入的方法必须是静态的。
This makes you call a static method like it was declared in the scope of this class: 这使您可以调用静态方法,就像在此类的范围内声明的那样:
someMethod();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.