我正在使用Java构建模拟游戏。我有一个界面," Critter"和抽象类" AbstractCritter"。我所有的"小动物"使用这两个来定义。
小动物
public interface Critter {
// create constants
// each holds a unique integer value
final int NORTH = 1;
final int WEST = 2;
final int SOUTH = 3;
final int EAST = 4;
final int CENTER = 5;
// create abstract methods
public char getChar();
public int getMove(CritterInfo theInfo);
}
AbstractCritter
public abstract class AbstractCritter implements Critter{
// create char to hold a particular critter
private char critterChar;
public AbstractCritter(final char theChar) {
critterChar = theChar;
}
public char getChar() {
return critterChar;
}
}
示例生物:
public class Stone extends AbstractCritter {
public Stone(char S) {
super(S);
// This is the main constructor for stone
}
public int getMove(CritterInfo theInfo) {
// The stone cannot move.
return 5;
}
}
主循环:
public final class CritterMain {
/** private constructor to inhibit instantiation. */
private CritterMain() {
// Do not instantiate objects of this class
throw new IllegalStateException();
}
/**
* The start point for the CritterMain application.
*
* @param theArgs command line arguments - ignored
*/
public static void main(String[] theArgs) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CritterFrame frame = new CritterFrame();
frame.add(100, Stone.class);
frame.add(50, Bat.class);
frame.add(25, Frog.class);
frame.add(25, Mouse.class);
frame.add(25, Turtle.class);
frame.add(25, Wolf.class);
frame.start();
}
});
}
}
每当我尝试运行主要的CritterMain时,我就会发现这个奇怪的错误,我无法在谷歌的任何地方找到:" 线程中的异常" AWT-EventQueue-0" java.lang.RuntimeException:没有类Stone的零参数构造函数"
这与我如何定义我的生物有关。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
创建类的实例时,可以使用其中一个可用的构造函数。 构造函数可能没有参数,也可能没有零参数。
如果您没有声明没有参数的构造函数并尝试实例化没有参数的类,您显然会收到错误。
所以只是制作一个没有参数的构造函数,就会停止错误。