super()方法在Java中

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年7月30日 05:27:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63162684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定