super()用于调用父构造函数吗? 请解释super()。
当前回答
来源文章:Java:调用super()
是的。Super(…)将调用超类的构造函数。
说明:
独立的例子:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
打印:
Constructing an animal: From Dog constructor
Constructing a dog.
其他回答
来源文章:Java:调用super()
是的。Super(…)将调用超类的构造函数。
说明:
独立的例子:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
打印:
Constructing an animal: From Dog constructor
Constructing a dog.
我们可以用SUPER做什么?
访问超类成员
如果你的方法覆盖了它的一些超类的方法,你可以通过使用关键字super来调用被覆盖的方法,比如super. methodname ();
调用超类构造函数
如果构造函数没有显式调用超类构造函数,Java编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会得到编译时错误。
看看下面的代码:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class of the top layer in the inheritance tree.And then all the way down the inheritance tree.The reason why this is possible to happen is that the Java compiler automatically inserts a call to the no-argument constructor of the superclass.If there's no non-argument constructor in the superclass and the subclass doesn't explicitly say which of the constructor is to be executed in the superclass,you'll get a compile-time error.
类的构造函数,在上面的代码中,如果我们想成功地创建Wolf对象 类必须执行。在这个过程中,Animal中的双参数构造函数 类被调用。同时,它显式地调用同一个参数中的单参数构造函数 类和单参数构造函数隐式调用生物中的非参数构造函数 类和非参数构造函数再次隐式调用Object中的空构造函数 类。
是的,super()(小写)调用父类的构造函数。可以包含参数:super(foo, bar)
还有一个超级关键字,您可以在方法中使用它来调用超类的方法
“Java super”的快速谷歌会导致这样的结果
调用无参数的超级构造函数只是浪费屏幕空间和程序员时间。编译器生成的代码完全相同,不管你写不写。
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
例如,在selenium自动化中,你有一个PageObject,它可以像这样使用它的父类构造函数:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?