Java 从超类继承构造函数?
我有一个名为Robot.java的类:Java 从超类继承构造函数?,java,class,oop,object,Java,Class,Oop,Object,我有一个名为Robot.java的类: class Robot { String name; int numLegs; float powerLevel; Robot(String productName) { name = productName; numLegs = 2; powerLevel = 2.0f; } void talk(String phrase) { if (powerLevel >= 1.0f) { System.o
class Robot {
String name;
int numLegs;
float powerLevel;
Robot(String productName) {
name = productName;
numLegs = 2;
powerLevel = 2.0f;
}
void talk(String phrase) {
if (powerLevel >= 1.0f) {
System.out.println(name + " says " + phrase);
powerLevel -= 1.0f;
}
else {
System.out.println(name + " is too weak to talk.");
}
}
void charge(float amount) {
System.out.println(name + " charges.");
powerLevel += amount;
}
}
public class TranslationRobot extends Robot {
// class has everything that Robot has implicitly
String substitute; // and more features
TranslationRobot(String substitute) {
this.substitute = substitute;
}
void translate(String phrase) {
this.talk(phrase.replaceAll("a", substitute));
}
@Override
void charge(float amount) { //overriding
System.out.println(name + " charges double.");
powerLevel = powerLevel + 2 * amount;
}
}
还有一个名为TranslationRobot.java的子类:
class Robot {
String name;
int numLegs;
float powerLevel;
Robot(String productName) {
name = productName;
numLegs = 2;
powerLevel = 2.0f;
}
void talk(String phrase) {
if (powerLevel >= 1.0f) {
System.out.println(name + " says " + phrase);
powerLevel -= 1.0f;
}
else {
System.out.println(name + " is too weak to talk.");
}
}
void charge(float amount) {
System.out.println(name + " charges.");
powerLevel += amount;
}
}
public class TranslationRobot extends Robot {
// class has everything that Robot has implicitly
String substitute; // and more features
TranslationRobot(String substitute) {
this.substitute = substitute;
}
void translate(String phrase) {
this.talk(phrase.replaceAll("a", substitute));
}
@Override
void charge(float amount) { //overriding
System.out.println(name + " charges double.");
powerLevel = powerLevel + 2 * amount;
}
}
编译TranslationRobot.java时,出现以下错误:
TranslationRobot.java:5: error: constructor Robot in class Robot cannot be applied to given types;
TranslationRobot(String substitute) {
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
我知道这指的是从超类继承,但我不太明白问题所在。这是因为子类在构造时总是需要调用其父类的构造函数。如果父类具有无参数构造函数,则会自动执行此操作。但是您的
Robot
类只有一个构造函数,它接受字符串,因此您需要显式调用它。这可以通过super
关键字来完成
TranslationRobot(String substitute) {
super("YourProductName");
this.substitute = substitute;
}
或者,如果您想给每个TranslationRobot
一个唯一的产品名称,您可以在构造函数中使用一个额外的参数并使用该参数:
TranslationRobot(String substitute, String productName) {
super(productName);
this.substitute = substitute;
}
构造函数不是继承的。太棒了,谢谢,只要它是字符串,我在超级方法中放什么就重要了吗?我可以写Robot.name吗?@user6731064你可以放任何你想要的东西(只要是字符串),但是这个.name
-我想这就是你的意思-不会做你想要的。请记住,name
还没有值。这就是构造器的作用。我猜你想要的是让TranslationRobot
在它的构造函数中取两个String
s,并使用其中一个作为super
的参数。