java,用main类的构造函数扩展类有参数

时间:2010-01-13 11:03:21

标签: 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) {
    //}
}

我该如何编写正确的语法? 并且错误是“构造函数不能应用于给定类型”

3 个答案:

答案 0 :(得分:40)

您可以为构造函数定义所需的任何参数,但是必须将超类的一个构造函数作为您自己的构造函数的第一行。这可以使用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
    }

}

答案 1 :(得分:4)

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

super(pFn, pWidth, pHeight);

由您决定是否希望类的构造函数具有相同的参数并将它们传递给超类构造函数:

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

或传递其他内容,例如:

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

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

答案 2 :(得分: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);
    }
}