英文:
super() method in Java
问题
class Animal {
Animal(){
super();
}
}
class Bird extends Animal {
Bird(String name){
System.out.println(name);
}
Bird(){
System.out.println("Unknown");
}
}
public class WhizSuperKeyWord {
public static void main(String[] args) {
new Bird("Parrot");
}
}
你好,这是我的第一篇帖子。我正在学习核心Java。你能帮我理解父类中super()方法的用途吗?我知道super()用于子类中调用父类的构造方法。我对父类中的super()方法的作用感到困惑。this()用于父类中调用当前类的构造方法。非常感谢。
英文:
class Animal {
Animal(){
super();
}
}
class Bird extends Animal {
Bird(String name){
System.out.println(name);
}
Bird(){
System.out.println("Unknown");
}
}
public class WhizSuperKeyWord {
public static void main(String[] args) {
new Bird("Parrot");
}
}
Hi, this is my first post. I am learning Core Java. Can you please help me understand what's the use of super() method in parent class. I understand super() is used in Child class to invoke constructor of Parent class. I am puzzled what is super() method doing in Parent class. this() is used in Parent class to invoke constructor of current class.
Many thanks.
答案1
得分: 2
这是毫无意义的。Java中的所有对象都继承自Object
类。对于没有显式超类的类,Java会自动在构造函数中插入隐式的super()
调用,因此Animal
中对super()
的调用是没有意义的。
英文:
It is pointless. All objects in Java inherit from the Object
class. Java automatically inserts an implicit super()
call in constructors of classes with no explicit superclass, so the call to super()
in Animal
is pointless.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论