标题: 关于内部类的使用问题 [打印本页] 作者: 光sail 时间: 2012-4-18 23:03 标题: 关于内部类的使用问题 这是内部类的程序
class One{
int i;
class Two{
int j;
int funTwo(){
int result = i+j;
return result;
}
}
}
运行程序1
public class Test{
public static void main(String args []){
One one = new One();
One.Two two =new One().new Two();
one.i = 5;
two.j = 6;
int result = two.funTwo();
System.out.println(result);
运行程序2
public class Test{
public static void main(String args []){
One one = new One();
One.Two two=one.new Two();
one.i = 5;
two.j = 6;
int result = two.funTwo();
System.out.println(result);
结果应该是一样的,可为什么第一个程序运行的结果是6. 第二个是11呢作者: 张卯 时间: 2012-4-18 23:12
One.Two two =new One().new Two();这里你又新new了一个One对象,i默认为0
One.Two two=one.new Two();这个One就是同一个了作者: liuyang 时间: 2012-4-18 23:17
楼主一定是以为
One.Two two =new One().new Two();
与One.Two two=one.new Two();
是等价的,实际上不是
System.out.println(one==new One());
上面那句话打印的是false,所以那两句代码不是等价的,结果自然不同了。作者: 小鹿叙鹿 时间: 2012-4-19 00:02
1:在第一个程序中,创建的One one = new One()中,创建了一个One对象,之后又创建了One.Two two =new One().new Two(),这时候two会创建一个外部类one与内部类two,此时two中one会把One one = new One()中的one给覆盖掉,当然其中的i 的值也就为0,所以相加为0.在这个题中,因为创建内部类的时候,必须先创建外部类。
2:在第二道程序中
刚好与1相反,因为外部类已经创建好。在One.Two two =new One().new Two()中,并没有覆写one,所以相加就是11.作者: 邓斌 时间: 2012-4-19 00:04
仔细琢磨后。用了构造函数初始化实验了下。
主要是第一个程序创建了3个对象。
第二个程序创建了2个对象。。
代码注释了下。