MikeJ
MikeJ

Reputation: 53

Calling method from one class to another

Starting to learn about UML diagrams, and how to interact between classes. Stuck on how to call this method from the Player class to the main method class. (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

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

Upvotes: 0

Views: 104

Answers (3)

kmera
kmera

Reputation: 1745

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. 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.

Upvotes: 0

Alan
Alan

Reputation: 822

In a main(...) method, if you call another classes method directly like: MyClass.doSomething() then the method doSomething() must be declared static. Otherwise, you need to make an instance of the class like this:

MyClass clazz = new MyClass();

Then call its method: clazz.doSomething();

Hope this helps.

Upvotes: 1

Marco Acierno
Marco Acierno

Reputation: 14847

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.

Upvotes: 1

Related Questions