Reputation: 25
I have been making a Tetris-like game in Java recently, I have a interface IBlocks which goes over ConsBlock
and EmptyBlock
(ConsBlock
is a list with a block at the beginnning and a IBlock
list at the end, for some reason that's the way my teacher wanted it).
I have the getfirst()
function in the interface:
public interface IBlocks{
//returns the first block in a list of blocks
public Resting getfirst();
(A Resting
is one block in the Game)
Then, in the ConsBlock class, I have:
public class ConsBlock implements IBlocks{
//returns the first block in a list of blocks
public Resting getfirst(){
return this.first;
But in the EmptyBlock
class, I want it to return something that would be similar to saying there isn't one. I tried returning null
, but that gave me a null pointer exception due to that fact that the function in the interface tells it to return a Resting
. What would be the best way to represent an empty one without returning a Resting with random numbers?
Upvotes: 0
Views: 70
Reputation: 32323
public interface IResting;
public class Resting implements IResting;
Then
public class EmptyResting implements IResting {
@Override
public Object sampleMethod() {
// return what an empty block ought to return
}
}
Further reading: http://en.wikipedia.org/wiki/Null_Object_pattern
Response to your comment: you still need to do:
public class EmptyBlock implements IBlocks {
@Override
public IResting getFirst() {
return new EmptyResting();
}
}
Note that your IBlocks
and ConsBlock
classes need to return an IResting
not a Resting
Make sure to read that wiki link!
Upvotes: 1
Reputation: 16
I could be off-base with this but, I believe with your method header it is asking to have a Resting returned. Is there any way you can create a boolean object and have that returned? maybe name it something like empty and if it is empty it returns true and if it is not empty it returns false? Another suggestion would be to manually set Resting to 0 if it meets the criteria for being set to zero such as if (condition is met) { returnedResting = 0; }.
Upvotes: 0