【问题标题】:this() and this这个()和这个
【发布时间】:2012-02-01 07:02:12
【问题描述】:

Java 有 this() 吗?

如果是这样,thisthis() 有什么区别?

【问题讨论】:

  • 你问过thisthis()之间的区别,那你为什么选择

标签: java this


【解决方案1】:

this 是对当前实例的引用。 this() 调用默认构造函数。 super()显式调用超类的默认构造函数。

【讨论】:

  • 所以super是对超类的引用?
  • @JJ Liu 是的,没错。 (: 所以你可以通过super.aSuperMethod(var1, var2) 显式调用受保护/公共的超级方法
【解决方案2】:

this 是对当前对象的引用。 this() 是对默认构造函数的调用;它仅在另一个构造函数中是合法的,并且仅作为构造函数中的第一条语句。您还可以调用super() 来调用超类的默认构造函数(同样,仅作为构造函数的第一条语句)。事实上,如果代码中不存在this()super()(带或不带参数),编译器会自动插入。例如:

public class A {
    A() {
       super(); // call to default superclass constructor.
    }

    A(int arg) {
        this(); // invokes default constructor
        // do something special with arg
    }

    A(int arg, int arg2) {
        this(arg); // invokes above constructor
        // do something with arg2
    }
}

【讨论】:

  • 谢谢,当你做super()时,你总是调用默认的无参数超类构造函数吗?我的意思是,当您说默认构造函数时,您总是指没有参数的构造函数吗?
  • @JJLiu - 如果超类定义了带有 args 的构造函数,您可以调用 super(args)
【解决方案3】:

是的,Java 有this()this() 为当前类调用构造函数的无参数重载。 this 是对当前类的实例(对象)的引用。

【讨论】:

    【解决方案4】:

    thisjava中的关键字,用于保存当前对象的引用ID。
    this() 是对java program 中默认构造函数的调用。

    this() 的代码 sn-p:

    class ThisTest{
        ThisTest(){
            System.out.println("this is the default constructor of your class");
        }
        ThisTest(int val){
            this();
            System.out.println("this is the parameterized constructor of your class and the passed value is "+val);
        }
        public static void main(String...args){
            ThisTest tt=new ThisTest(10);
        }
    }
    

    在上面的代码中,您使用参数化构造函数创建了类的对象,但this() 必须是您的任何构造函数中第一个调用任何其他构造函数的对象。
    也可以把上面的代码改成:

    ThisTest(){
        this(10);
        //above code
    }
    ThisTest(int val){
        //above code
    }
    public static void main(string...args){
        ThisTest tt=new ThisTest();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2014-09-07
      • 2014-01-31
      相关资源
      最近更新 更多