一,用构造函数创建实例的问题。
问题:
Integer i1 = new Integer(40);
Integer i2 = new Integer(40);
i1==i2,i1.equals(i2)这两个表达式的值是多少?
i1==i2=false;i1.equals(i2)=true;
因为前者表示创建对象(对象的引用),等号后面表示赋值给对象(对象的内容);所以i1和i2值是相等的,但是是两个对象,所以i1!=i2。
二,this关键字。
1,this表示当前对象的引用,如在方法中
return this;表示return的是该class的实例,其方法的类型应该和该实例一样。

public class LeafTest ...{
int i = 0;
LeafTest increment()...{
i++;
return this;
}

void print()...{
System.out.println("i="+i);
}
/** *//**
* @param args
*/
public static void main(String[] args) ...{
// TODO Auto-generated method stub
LeafTest l = new LeafTest();
l.increment().increment().increment().print();
}
}/**Output i = 3; *///~
2,可以在构造器中引用构造器,但是要注意几点
a:用this构造实例必须在最始处。
b:只有构造函数中允许调用其他构造函数。
package w4;

public class ThisTest2 ...{
int pCount = 0;
String s = "init value";
ThisTest2(int p)...{
pCount = p;
System.out.println("p="+p);
}

ThisTest2(String ss)...{
s = ss;
System.out.println("s="+s);
}

ThisTest2(String s,int p)...{
this(p);
this.s = s;
System.out.println("String$int");
}

ThisTest2()...{
this("hi",47);
System.out.println("aaa");
}

void pr()...{
// this(11);不能在非构造函数中使用
System.out.println("p="+pCount+" s="+s);
}

/** *//**
* @param args
*/
public static void main(String[] args) ...{
// TODO Auto-generated method stub
ThisTest2 t = new ThisTest2();
t.pr();
}

}/** *//**Output:
*p=47
*String$int
*aaa
*p=47 s=hi
*///~
本文探讨了Java中使用构造函数创建对象实例的问题,并详细解释了如何使用this关键字来引用当前对象实例及其在构造函数中的应用。
3427

被折叠的 条评论
为什么被折叠?



