Java 如何从另一个类调用方法

Java 如何从另一个类调用方法,java,methods,Java,Methods,你好,我是面向对象编程新手。通常我会使用构造函数调用一个方法。但在这种情况下,它似乎不起作用。 我想从CommandWords类调用getCommands()方法到Game类。谁能帮助我理解我是如何做到这一点的?谢谢 public class Game() { private void printHelp() { System.out.println("You are " + currentRoom.getDescription()); System.out.p

你好,我是面向对象编程新手。通常我会使用构造函数调用一个方法。但在这种情况下,它似乎不起作用。 我想从CommandWords类调用getCommands()方法到Game类。谁能帮助我理解我是如何做到这一点的?谢谢

public class Game() {
    private void printHelp() 
    {
    System.out.println("You are " + currentRoom.getDescription());
    System.out.println();
    System.out.println("Your command words are:");
    System.out.println("   go quit help");
    //getCommands();
    System.out.println();
    System.out.print("Your exits are: ");
    if(currentRoom.northExit != null) {
        System.out.print("north ");
    }
    if(currentRoom.eastExit != null) {
        System.out.print("east ");
    }
    if(currentRoom.southExit != null) {
        System.out.print("south ");
    }
    if(currentRoom.westExit != null) {
        System.out.print("west ");
    }
    System.out.println();
    }
}
我要从中调用方法getCommands()的类

公共类命令词
{
//保存所有有效命令字的常量数组
私有静态最终字符串[]有效命令={
“去”、“退出”、“帮助”
};
//方法,该方法获取有效命令的字符串表示形式
公共字符串getCommands(){
字符串打印机=”;
对于(int i=0;i您不需要使用构造函数“调用方法”。您需要创建CommandWords类的实例,然后对其调用方法:

public class Game() {
    private void printHelp() 
    {
    System.out.println("You are " + currentRoom.getDescription());
    System.out.println();
    System.out.println("Your command words are:");
    System.out.println("   go quit help");
    CommandWords words = new CommandWords();
    String results = words.getCommands();

阅读了吗?

您可以创建新的对象实例并通过该实例调用方法

CommandWords commandWords = new CommandWords();
String commands = commandWords.getCommands();
System.out.println(commands);

将上述行替换为//getCommands();

无需对构造函数执行任何操作。只需创建CommandWords类的实例并调用getCommands方法

private void printHelp() 
{
System.out.println("You are " + currentRoom.getDescription());
System.out.println();
System.out.println("Your command words are:");
System.out.println("   go quit help");
CommandWords command_words=new CommandWords();
command_words.getCommands();
System.out.println();

如果将
getCommands()
更改为
static
方法,则可以通过如下操作调用它:
String cmds=CommandWords.getCommands();
CommandWords commandWords = new CommandWords();
String commands = commandWords.getCommands();
System.out.println(commands);
private void printHelp() 
{
System.out.println("You are " + currentRoom.getDescription());
System.out.println();
System.out.println("Your command words are:");
System.out.println("   go quit help");
CommandWords command_words=new CommandWords();
command_words.getCommands();
System.out.println();