java,用主类的构造函数扩展类有参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2056097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java, extending class with the constructor of main class has parameter
提问by r4ccoon
hei. the language is java. i want to extend this class which the constructor has parameters.
嘿。语言是java。我想扩展这个构造函数有参数的类。
this is the main class
这是主要课程
public class CAnimatedSprite {
public CAnimatedSprite(String pFn, int pWidth, int pHeight) {
}
}
this is the child class
这是儿童班
public class CMainCharacter extends CAnimatedSprite {
//public void CMainCharacter:CAnimatedSprite(String pFn, int pWidth, int pHeight) {
//}
}
how do i write the correct syntax? and the error is "constructor cannot be applied to given types"
我如何编写正确的语法?并且错误是“构造函数不能应用于给定类型”
采纳答案by Thomas L?tzer
You can define any arguments you need for your constructor, but it is necessary to call one constructor of the super class as the first line of your own constructor. This can be done using super()
or super(arguments)
.
您可以为构造函数定义任何需要的参数,但必须调用超类的一个构造函数作为您自己的构造函数的第一行。这可以使用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
}
}
回答by Tadeusz Kopec
The first statement of your constructor must be a call to superclass constructor. The syntax is:
构造函数的第一条语句必须是对超类构造函数的调用。语法是:
super(pFn, pWidth, pHeight);
It is up to you to decide, whether you want constructor of your class to have same parameters and just pass them to superclass constructor:
由您决定,是否希望类的构造函数具有相同的参数并将它们传递给超类构造函数:
public CMainCharacter(String pFn, int pWidth, int pHeight) {
super(pFn, pWidth, pHeight);
}
or pass something else, like:
或传递其他内容,例如:
public CMainCharacter() {
super("", 7, 11);
}
And don't specify return type for constructors. It's illegal.
并且不要为 constructors 指定返回类型。这是非法的。
回答by Alex Ntousias
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);
}
}