Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中何时调用this()和何时调用super()?_Java - Fatal编程技术网

在java中何时调用this()和何时调用super()?

在java中何时调用this()和何时调用super()?,java,Java,有谁能告诉我在java构造函数中super()调用和this()调用的区别吗 super()表示超类(父类),this()表示当前类。super()调用类的父构造函数,this()调用类中定义的构造函数 //Example of super() class parent { parent() { } } class child() { child() { super(); //Go to parent class constructor } }

有谁能告诉我在java构造函数中super()调用和this()调用的区别吗

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()引用基类/父类。可以在构造函数中使用以调用父构造函数,但必须在构造函数的声明中执行。

超级()的
用于调用超类的构造函数
this()
引用当前类

这里有好的SO链接


这意味着您正在将对象构造的一部分委托给另一个构造函数,即
super()
一个在超类中定义的构造函数和
this()
一个在同一类中定义的构造函数。

一个可以通过谷歌搜索的问题。super()用于调用超类的构造函数。this()是当前类
这个
指的是当前(这个)类的构造函数
super
指超类的构造函数。