简体   繁体   English

从一个类到另一个类的调用方法

[英]Calling method from one class to another

Starting to learn about UML diagrams, and how to interact between classes. 开始学习UML图,以及如何在类之间进行交互。 Stuck on how to call this method from the Player class to the main method class. 坚持如何将此方法从Player类调用到main方法类。 (MY instructions say I'm not allowed to use constructors) (我的指示说我不允许使用构造函数)

Player class = 玩家类=

 public String askForGuess()
{
    System.out.println("Enter your guess: ");
    String userGuess = keyboard.nextLine();
    return userGuess;
}

Bagel class(includes main method, trying to call the askForGuess method Bagel类(包括main方法,试图调用askForGuess方法

Player.askForGuess(); //Java is saying I need to change it to static, is that true?

Yes, if you want to call a method using class name, the method should be static ! 是的,如果要使用类名调用方法,则该方法应该是静态的

If you don't want to make the method static, you should create an instance of the class then call the method. 如果您不想使方法成为静态,则应创建该类的实例,然后调用该方法。

In this case, make the method static have a sense since don't have any "relationship" with the fields/methods of the class. 在这种情况下,使方法静态有意义,因为与类的字段/方法没有任何“关系”。

In a main(...) method, if you call another classes method directly like: MyClass.doSomething() then the method doSomething() must be declared static. 在main(...)方法中,如果直接调用另一个类方法,如:MyClass.doSomething(),则必须将方法doSomething()声明为static。 Otherwise, you need to make an instance of the class like this: 否则,您需要创建类的实例,如下所示:

MyClass clazz = new MyClass(); MyClass clazz = new MyClass();

Then call its method: clazz.doSomething(); 然后调用它的方法:clazz.doSomething();

Hope this helps. 希望这可以帮助。

As others have pointed out making the method static will solve your problem. 正如其他人指出的那样,使方法静态可以解决您的问题。 What they didn't tell you is WHY . 他们没有告诉你的是为什么

static methods are associated with the class itself, not with any particular object. static方法与类本身相关联,而不与任何特定对象相关联。 you don't have to create an object to use such a static method. 您不必创建对象来使用这种静态方法。 even if you create thousand objects there will still only be one instance of the method. 即使您创建了数千个对象,仍然只有该方法的一个实例。

class Foo{
    void foo(){...}
}

new Foo().foo(); //method is part of each object


class Bar {
    static void bar(){...}
}

Bar.foo();  //method is at the class level

Find out more about it here . 在这里了解更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM