【问题标题】:When to call this() and when to call super() in java? [duplicate]java中什么时候调用this(),什么时候调用super()? [复制]
【发布时间】:2014-03-27 23:40:13
【问题描述】:

谁能告诉我java构造函数中super()调用和this()调用有什么区别?

【问题讨论】:

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

标签: java


【解决方案1】:

super() 表示超类(父类),this() 表示当前类。

【讨论】:

    【解决方案2】:

    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)
        {
    
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      this() 为同一个类调用另一个构造函数。在这种情况下,参数 0 为 1。

      super() 调用超类的构造函数。

      【讨论】:

        【解决方案4】:

        super() 调用超类的无参数构造函数,this() 调用当前类的无参数构造函数。

        【讨论】:

          【解决方案5】:

          super() 指的是基类/父类。可以在构造函数中调用父构造函数,但必须在构造函数的声明中完成。

          【讨论】:

            【解决方案6】:

            super() 用于调用超类的构造函数。 this() 指的是当前类。

            这里有很好的 SO 链接。

            this and super in java

            Difference between "this" and"super" keywords in Java

            【讨论】:

              【解决方案7】:

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

              【讨论】:

                猜你喜欢
                • 2015-07-29
                • 2019-12-25
                • 2011-05-04
                • 2014-04-29
                • 2013-10-19
                • 2010-10-18
                • 2016-03-08
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多