3 回答

TA贡献1812条经验 获得超5个赞
精确 调用始终super()是多余的。它明确地在做否则会隐式地做的事情。这是因为如果您省略对超级构造函数的调用,则无论如何都将自动调用无参数的超级构造函数。并不是说这是不好的风格。有些人喜欢露骨。
但是,当超级构造函数采用您要从子类传递的参数时,它才变得有用。
public class Animal {
private final String noise;
protected Animal(String noise) {
this.noise = noise;
}
public void makeNoise() {
System.out.println(noise);
}
}
public class Pig extends Animal {
public Pig() {
super("Oink");
}
}

TA贡献1828条经验 获得超4个赞
super当您想在父类中重写某个方法时要从父类调用方法时,也可以在子类中使用该关键字。
例:
public class CellPhone {
public void print() {
System.out.println("I'm a cellphone");
}
}
public class TouchPhone extends CellPhone {
@Override
public void print() {
super.print();
System.out.println("I'm a touch screen cellphone");
}
public static void main (strings[] args) {
TouchPhone p = new TouchPhone();
p.print();
}
}
在此,该行super.print()调用print()超类的方法CellPhone。输出将是:
I'm a cellphone
I'm a touch screen cellphone

TA贡献1878条经验 获得超4个赞
您可以将其用作子类构造函数的第一行,以调用其父类的构造函数。
例如:
public class TheSuper{
public TheSuper(){
eatCake();
}
}
public class TheSub extends TheSuper{
public TheSub(){
super();
eatMoreCake();
}
}
构造的实例TheSub将同时调用eatCake()和eatMoreCake()
添加回答
举报