Java。 class 中的超级调用扩展了对象
Java. Super call in class which extends Object
经常看到这样的代码:
class MyClass{
private int a;
public MyClass(int a){
super(); //what is the purpose of this method call?
this.a = a;
}
//other class methods here
}
如果 class 扩展对象,super() 调用调用 Object 构造函数,据我所知,它什么都不做。那么为什么需要调用 super() 呢?我对那个特殊情况很感兴趣,当 super() 什么都不做,因为它只是调用 Object()。
首先我建议阅读源代码 - documentation.
然后引用jb-nizet's answer:
Note that this explicit call is unnecessary since the compiler would add it for you. You only need to add a super() call in a constructor when you want to invoke a superclass constructor with arguments.
在Java中,super
指的是父class。我们可以通过两种方式使用它:
super()
正在调用父 class 的构造函数。 super.toString()
将调用父 class' 实现 toString
方法。
在你的例子中:
class MyClass{
private int a;
public MyClass(int a){
super(); //what purpose of this?
this.a = a;
}
//other class methods here
}
调用的是Object
的构造函数,空空如也,故作迂腐,但如果我们修改一下:
class Foo extends Bar{
private int a;
public Foo(int a){
super(); //what purpose of this?
this.a = a;
}
//other class methods here
}
表示先调用Bar
的构造函数
我之前描述的另一种用法是:
class Bar {
public String toString() {
return "bar";
}
}
class Foo extends Bar{
String foo = "foo";
public Foo(){
super(); //what purpose of this?
}
public String toString() {
super.toString()
}
将导致返回 "bar"。
经常看到这样的代码:
class MyClass{
private int a;
public MyClass(int a){
super(); //what is the purpose of this method call?
this.a = a;
}
//other class methods here
}
如果 class 扩展对象,super() 调用调用 Object 构造函数,据我所知,它什么都不做。那么为什么需要调用 super() 呢?我对那个特殊情况很感兴趣,当 super() 什么都不做,因为它只是调用 Object()。
首先我建议阅读源代码 - documentation. 然后引用jb-nizet's answer:
Note that this explicit call is unnecessary since the compiler would add it for you. You only need to add a super() call in a constructor when you want to invoke a superclass constructor with arguments.
在Java中,super
指的是父class。我们可以通过两种方式使用它:
super()
正在调用父 class 的构造函数。 super.toString()
将调用父 class' 实现 toString
方法。
在你的例子中:
class MyClass{
private int a;
public MyClass(int a){
super(); //what purpose of this?
this.a = a;
}
//other class methods here
}
调用的是Object
的构造函数,空空如也,故作迂腐,但如果我们修改一下:
class Foo extends Bar{
private int a;
public Foo(int a){
super(); //what purpose of this?
this.a = a;
}
//other class methods here
}
表示先调用Bar
的构造函数
我之前描述的另一种用法是:
class Bar {
public String toString() {
return "bar";
}
}
class Foo extends Bar{
String foo = "foo";
public Foo(){
super(); //what purpose of this?
}
public String toString() {
super.toString()
}
将导致返回 "bar"。