【发布时间】:2012-02-01 07:02:12
【问题描述】:
Java 有 this() 吗?
如果是这样,this 和 this() 有什么区别?
【问题讨论】:
-
你问过
this和this()之间的区别,那你为什么选择
Java 有 this() 吗?
如果是这样,this 和 this() 有什么区别?
【问题讨论】:
this和this()之间的区别,那你为什么选择
this 是对当前实例的引用。 this() 调用默认构造函数。 super() 是显式调用超类的默认构造函数。
【讨论】:
super是对超类的引用?
super.aSuperMethod(var1, var2) 显式调用受保护/公共的超级方法
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()时,你总是调用默认的无参数超类构造函数吗?我的意思是,当您说默认构造函数时,您总是指没有参数的构造函数吗?
super(args)。
是的,Java 有this()。 this() 为当前类调用构造函数的无参数重载。 this 是对当前类的实例(对象)的引用。
【讨论】:
this是java中的关键字,用于保存当前对象的引用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();
}
【讨论】: