简体   繁体   English

我如何称呼另一个类中的公共静态void。

[英]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.

相关问题 如何从公共static void main到另一个类调用变量? - How do I call a variable from the public static void main to another class? 如何在Fragment类中从公共静态void调用到非静态公共void - How can call from public static void to not static public void in Fragment class 如何在 Java 中调用公共 static void main(String[] args) class 中的方法? - How to call a method inside the public static void main(String[] args) class in Java? 使用其他类的公共静态HashTable的同步方法。 如何使该方法线程安全? - synchronized method that use a public static HashTable from other class. How can I make this method thread safe? 我应该把 public static void main(String[] args) 放在哪里? - Where do I put public static void main(String[] args)? Java-如何将通过公共静态void方法读取到程序中的数据保存到String中? - Java- how do I save data that is being read into my program by a public static void method into a String? 我在哪里添加公共 static void main(String[] args) - where do i add the public static void main(String[] args) 如何从另一个类中的 void 方法调用变量 - How do I call a variable from a void method in another class 如何获取Java类的所有公共静态方法? - How do I get all public static methods of a class in Java? 如何通过对类的引用来调用instanceof。 - How can I call instanceof by a reference to a class.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM