【发布时间】:2014-03-27 23:40:13
【问题描述】:
谁能告诉我java构造函数中super()调用和this()调用有什么区别?
【问题讨论】:
-
一个可以用谷歌搜索的问题。 super() 用于调用超类的构造函数。 this() 是当前类
-
this指的是(猜猜看...)当前(this)类的构造函数。super指的是超类的构造函数。
标签: java
谁能告诉我java构造函数中super()调用和this()调用有什么区别?
【问题讨论】:
this 指的是(猜猜看...)当前(this)类的构造函数。 super 指的是超类的构造函数。
标签: java
super() 表示超类(父类),this() 表示当前类。
【讨论】:
super()调用类的父构造函数,this()调用类中定义的构造函数。
//Example of super()
class parent
{
parent()
{
}
}
class child()
{
child()
{
super(); //Go to parent class constructor
}
}
//Example of this
class test
{
test()
{
this("a"); //go to test one argument constructor within the test class
}
test(String a)
{
}
}
【讨论】:
this() 为同一个类调用另一个构造函数。在这种情况下,参数 0 为 1。
super() 调用超类的构造函数。
【讨论】:
super() 调用超类的无参数构造函数,this() 调用当前类的无参数构造函数。
【讨论】:
super() 指的是基类/父类。可以在构造函数中调用父构造函数,但必须在构造函数的声明中完成。
【讨论】:
super() 用于调用超类的构造函数。 this() 指的是当前类。
这里有很好的 SO 链接。
【讨论】:
这意味着您将对象构造的一部分委托给另一个构造函数,super() 是定义在超类中的构造函数,this() 是定义在同一类中的构造函数。
【讨论】: