2010-01-13 133 views
21

hei。该语言是java。 我想扩展这个构造函数有参数的类。java,扩展类与主类的构造函数有参数

这是主类

public class CAnimatedSprite { 
    public CAnimatedSprite(String pFn, int pWidth, int pHeight) { 
    } 
} 

这是子类

public class CMainCharacter extends CAnimatedSprite { 

    //public void CMainCharacter:CAnimatedSprite(String pFn, int pWidth, int pHeight) { 
    //} 
} 

我怎样写正确的语法? 和错误是“构造函数不能应用于给定的类型”

回答

36

您可以定义您的构造函数所需的任何参数,但有必要调用超类的一个构造函数作为自己的构造函数的第一行。这可以使用super()super(arguments)完成。

public class CMainCharacter extends CAnimatedSprite { 

    public CMainCharacter() { 
     super("your pFn value here", 0, 0); 
     //do whatever you want to do in your constructor here 
    } 

    public CMainCharacter(String pFn, int pWidth, int pHeight) { 
     super(pFn, pWidth, pHeight); 
     //do whatever you want to do in your constructor here 
    } 

} 
+0

它的工作原理。谢谢。解决了这个语法问题。 – r4ccoon 2010-01-13 12:21:47

+0

如果我在根类中有多个构造函数,该怎么办?我需要为我的扩展类中的每个人做super()吗? – sammiwei 2012-01-30 19:07:46

3

构造函数的第一个语句必须是对超类构造函数的调用。语法是:

super(pFn, pWidth, pHeight); 

它是由你来决定,你是否希望你的类的构造函数具有相同的参数,只是将它们传递给父类的构造:

public CMainCharacter(String pFn, int pWidth, int pHeight) { 
    super(pFn, pWidth, pHeight); 
} 

或者通过什么的,像:

public CMainCharacter() { 
    super("", 7, 11); 
} 

而且不指定构造返回类型。这是非法的。

1
public class CAnimatedSprite { 
    public CAnimatedSprite(String pFn, int pWidth, int pHeight) { 
    } 
} 


public class CMainCharacter extends CAnimatedSprite { 

    // If you want your second constructor to have the same args 
    public CMainCharacter(String pFn, int pWidth, int pHeight) { 
     super(pFn, pWidth, pHeight); 
    } 
} 
相关问题