2012-12-19 46 views
5

我有一个扩展实体类球员:Java实际参数与形式参数不匹配,但它们的确如此?

球员:

public class Player extends Entity { 
    public Player(char initIcon, int initX, int initY) { 
     //empty constructor 
    } 
... 

实体:

public Entity(char initIcon, int initX, int initY) { 
     icon = initIcon; 
     x = initX; 
     y = initY; 
    } 
... 

这是一个很值得你期待什么,但对编译我收到一条错误消息:

Player.java:2: error: constructor Entity in class Entity cannot be applied to the given types: 
    public Player(char initIcon, int initX, int initY) 
required: char,int,int 
found: no arguments 
reason: actual and formal argument lists differ in length 

但它显然确实有必要的参数。这里发生了什么?谢谢!

+7

你为什么不这样做'超(聊天,INT,INT)'? – GGrec

回答

13

您需要通过初始化超类调用它的构造与super

public Player(char initIcon, int initX, int initY) { 
    super(initIcon, initX, initY); 
} 
7

你的超类构造函数有3个参数,似乎没有空的构造函数。因此,您的子类构造函数应该对传递值的超类构造函数进行显式调用。

public class Player extends Entity { 
    public Player(char initIcon, int initX, int initY) { 
     //empty constructor 
     super(initIcon,initX,initY); 
    } 
... 
2

您需要调用基类的构造函数明确地从延伸类的构造函数。你这样做,象这样的:

public class Player extends Entity { 
    public Player(char initIcon, int initX, int initY) { 
     super(initIcon, initX, initY); 
     // rest of player-specific constructor 
    } 
2

有一个超级构造函数没有显式调用(如在其他的答案或如下图所示) 所以VM将使用隐式的0参数的构造函数...但此构造函数不存在。所以,你必须做一个明确的调用一个有效的超级构造函数:

public class Player extends Entity { 
    public Player(char initIcon, int initX, int initY) { 
     super(initIcon,initX,initY); 
    } 
0

时,子类继承,那么父类的默认父类的构造函数中,默认情况下调用。 在上述情况下,您已经在Parent类中定义了参数构造函数,所以JVM不提供默认值,并且您的子类正在调用不存在的父级默认构造函数。 要么指定父类中的默认构造函数,要么使用super调用父类的参数构造函数。

public class Player extends Entity { 
public Player() 
{} 
public Player(char initIcon, int initX, int initY) { 
    //empty constructor 
} 

OR

public Player 
(char initIcon, int initX, int initY) { 
super(initIcon, initX, initY); 
} 
相关问题