Reputation: 595
I'm sorry if this title doesn't describe the problem properly but I wasn't sure how to describe it.
I have a method called changeToWhite()
that can be called on a Piece
e.g. Piece.changeToWhite()
but for me to be able to change the piece to white I need access to the piece so I decided to pass it in as an argument
e.g. Piece.changeToWhite(Piece)
The passing in as an argument seems unnecessary.
The toUpperCase()
functions does it somehow e.g. someString.toUpperCase()
How can I do this?
Upvotes: 1
Views: 66
Reputation: 3769
This is the difference between static and instance methods. In your example, calling Piece.changeToWhite()
is a static method, but you are trying to access instance variables (the type of piece).
You have two choices:
Piece p1 = new Piece(); p1.changeToWhite();
Upvotes: 3
Reputation: 120268
If you define changeToWhite
on a Piece
class, then on an instance you can use this
to get the reference to the current object. Something like:
class Piece {
private String color;
...
public void changeToWhite() {
this.color = 'white';
}
}
Note that when you define a method on a class, you need to have an instance on which to call the methods.
So
Piece piece1 = new Piece();
piece1.changeToWhite();
Note that the Java standard is to use uppercase to define a class (e.g. Piece
), and camel case (e.g. changeToWhite
) for instance methods and fields.
The OTHER way to do it would be to use a static method. In this case, the method belongs to the class, it doesn't have a this
context like instance methods do
class Piece {
private String color; // instance field
/**
Takes a piece instance as an argument, and operates on that.
*/
private static void changeToWhite(Piece piece) {
piece.setColor('white'); // assume setColor exists
}
}
but the first way is preferable.
Upvotes: 9