beyonchayyy
beyonchayyy

Reputation: 93

Using a private attribute through its getter method in another method of the same class

I'm very much new to the concept of OOP and for a project I'd have to make a card game with 2 players. I created a class called Player which has an private attribute called playerNumber, and many others. I created a method called playTurn which needs to use Player's private attributes such as playerNumber.

I tried to use it like this:

public static void playTurn(){  
    System.out.println("It's Player " + this.getPlayerNumber() + "'s turn.");
}

but Eclipse would give ask me either to make the getter method getPlayerNumber() static or the private attribute playerNumber static.

Is it possible to have remain the private PlayerNumber without static and still use the that attribute in another method, but in the same class?

Upvotes: 0

Views: 166

Answers (1)

rob
rob

Reputation: 1286

You cannot reference a non-static method or variable from a static context.

It looks like playTurn() should not be static since it requires access to an instance of Player.

See this answer

Upvotes: 3

Related Questions