【发布时间】:2015-07-14 00:11:36
【问题描述】:
如果this 和moving 瓦片具有相同的值,则public boolean mergesWith(Tile moving) 方法返回true。但是当我通过执行以下操作检查它们是否相同时:
if(this.value == temp.value){
return true;
}
然后它在temp.value 上显示错误,说值无法解析或不是字段。
我该如何解决这个问题?
类TwoNTile:
package Game2048;
// Concrete implementation of a Tile. TwoNTiles merge with each other
// but only if they have the same value.
public class TwoNTile extends Tile {
private int value;
// Create a tile with the given value of n; should be a power of 2
// though no error checking is done
public TwoNTile(int n){
value = n;
}
// Returns true if this tile merges with the given tile. "this"
// (calling tile) is assumed to be the stationary tile while moving
// is presumed to be the moving tile. TwoNTiles only merge with
// other TwoNTiles with the same internal value.
public boolean mergesWith(Tile moving){
Tile temp = moving;
if(this.value == temp.value){
return true;
}
else{
return false;
}
}
// Produce a new tile which is the result of merging this tile with
// the other. For TwoNTiles, the new Tile will be another TwoNTile
// and will have the sum of the two merged tiles for its value.
// Throw a runtime exception with a useful error message if this
// tile and other cannot be merged.
public Tile merge(Tile moving){
return null;
}
// Get the score for this tile. The score for TwoNTiles are its face
// value.
public int getScore(){
return -1;
}
// Return a string representation of the tile
public String toString(){
return "";
}
}
类平铺:
package Game2048;
// Abstract notion of a game tile.
public abstract class Tile{
// Returns true if this tile merges with the given tile.
public abstract boolean mergesWith(Tile other);
// Produce a new tile which is the result of merging this tile with
// the other. May throw an exception if merging is illegal
public abstract Tile merge(Tile other);
// Get the score for this tile.
public abstract int getScore();
// Return a string representation of the tile
public abstract String toString();
}
【问题讨论】:
-
Tile类中没有名为value的字段,您将Tile传递给方法,而不是TwoNTile -
但是如果
Tile类是abstract并且不能创建对象,这是唯一的方法吗,即在Tile类中声明一个int value? @xp500 -
您仍然可以从子类中调用抽象类的构造函数。所以可以将
value字段移到抽象类中,然后TwoNTile构造函数就可以调用super(value)
标签: java