public class a{
public b bb[] = new b[3]; public class b{
public void test(){
index = 9;
if (bb[0] == this) index = 0;
if (bb[1] == this) index = 1;
if (bb[2] == this) index = 2;
System.out.println(index);
}
}
public a(){
bb[0]=new b();
bb[1]=new b();
bb[2]=new b(); }
}
结果是index=0
我就不明白为什么bb[0]会等于this.我觉的应该每个类都是不同的地址呀
public b bb[] = new b[3]; public class b{
public void test(){
index = 9;
if (bb[0] == this) index = 0;
if (bb[1] == this) index = 1;
if (bb[2] == this) index = 2;
System.out.println(index);
}
}
public a(){
bb[0]=new b();
bb[1]=new b();
bb[2]=new b(); }
}
结果是index=0
我就不明白为什么bb[0]会等于this.我觉的应该每个类都是不同的地址呀
bb[1].test(); 1
bb[2].test(); 2其实楼主并没有描述清楚你的程序如何运行,而且结果应该有三行结果吧
public b bb[] = new b[3]; public class b{
public void test(){
int index = 9;
if (bb[0] == this) index = 0;
if (bb[1] == this) index = 1;
if (bb[2] == this) index = 2;
System.out.println(bb[0]);
System.out.println(bb[1]);
System.out.println(bb[2]);
System.out.println(this);
System.out.println(index);
}
}
public a(){
bb[0]=new b();
bb[1]=new b();
bb[2]=new b();
bb[0].test();
}
public static void main(String[] args){
a ad = new a(); }
}结果是:
a$b@35ce36
a$b@757aef
a$b@d9f9c3
a$b@35ce36
0
也就是说bb[0]和this的地址是一样的,不明白是什么原因
public void test(){
int index = 9;
if (bb[0] == this) index = 0;
if (bb[1] == this) index = 1;
if (bb[2] == this) index = 2;
System.out.println(bb[0]);
System.out.println(bb[1]);
System.out.println(bb[2]);
System.out.println(this);
System.out.println(index);
}这个时候的this对象就是bb[0]了。你可以换成bb[1].test();那么输出的就是1了。
其实从test()代码来看,作用主要是判断当前是b类的哪个对象调用了test()方法;具体在这里就是三个数组元素。现在调用的是bb[0].test();当然 if (bb[0] == this) index = 0;
条件为真。还有问题的关键就是this的意义,它是指调用该方法的当前对象。
还是代表当前调用这个类的对像