[英]How do I call a public static void that is in a different class.
I have 2 classes, MainActivity and MainGame. 我有2个课程,MainActivity和MainGame。 If I have a public static void in MainActivity, and one in MainGame.
如果我在MainActivity中有一个公共静态空洞,而在MainGame中有一个公共空洞。 How would I execute the one in MainGame from MainActivity?
我如何在MainActivity中的MainGame中执行一个?
For example, I have this: 例如,我有这个:
Main Activity: 主要活动:
public static void 1()
{
2();
}
Main Game: 主游戏:
public static void 2()
{
//blah blah blah
}
2 isn't a valid method name I think, but if it were you'd just do: 我认为2不是有效的方法名称,但是如果是,则可以这样做:
MainActivity.2();
but let's say it isn't and you called it two instead, then maybe you're looking for 但假设不是,您改称两个,那么也许您正在寻找
public class MainGame {
public static void one() {
System.out.println("called one()");
}
}
public class MainActivity {
public static void two() {
MainGame.one();
}
}
In Java All Names must start with a '_' or alphabet.
在Java中,所有名称都必须以“ _”或字母开头。
So, we can take the method names 1
as _1
and 2
as _2
. 因此,我们可以将方法名称
1
设为_1
并将2
名称设为_2
。
The syntax for calling static
methods in other classes is ClassName.MethodName(arguments)
. 在其他类中调用
static
方法的语法为ClassName.MethodName(arguments)
。
So, in this case you would change the code as follows: 因此,在这种情况下,您将更改代码,如下所示:
class MainActivity{
public static void _1()
{
MainGame._2();
}
}
class MainGame{
public static void _2()
{
//blah blah blah
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.