public class Ex45
{
public static void main(String[] args)
{
test x1=new test();
test x2=new test();
x2.x=x1;
x1.x=x2;
x1=null;
x2=null;
}
}class test
{
test x;
public test()
{
}
}我主要是不明白:这test x;定义了一个空句柄;
而在main方法里,用x2.x,x1.x这样用法,到底是个什么意思?
{
public static void main(String[] args)
{
test x1=new test();
test x2=new test();
x2.x=x1;
x1.x=x2;
x1=null;
x2=null;
}
}class test
{
test x;
public test()
{
}
}我主要是不明白:这test x;定义了一个空句柄;
而在main方法里,用x2.x,x1.x这样用法,到底是个什么意思?
{
public static void main(String[] args)
{
test x1=new test("对像x1");
test x2=new test("对像x2");
x1.prn();
x2.prn(); x2.x=x1;
x1.x=x2;
x1.x.prn();
x2.x.prn();
x1=null;
x2=null;
}
}class test
{
String classname;
test x;
public test(String name)
{
classname = name;
} public void prn()
{
System.out.println("现在你调用的是:"+classname+"的方法");
}
}首先你要明白什么是句柄,句柄就是指向对像的那变量。任何对象初始前都=null,直到使用了new语句或是直接给它赋值。上面的x1,x2就是一个句柄,也就是指向test类型的对像的变量,通过它我们可以访问对像里的方法(如:x1.prn(); x2.prn();)。因为对像x1,x2里都有一个test类型的句柄,我们可以将一个句柄赋值给它们,即x1.x=x2; x2.x=x1; ,这时x1.x就指向了对像x2,x2.x就指向了对像x1。这时我们就可以通它们,访问它们所指向的对像的方法。
即x1.x.prn();x2.x.prn();
public class Ex45
{
public static void main(String[] args)
{
test x1=new test(); //创建 Test 的一个实例
test x2=new test();x2.x=x1; //用一个具体对象引用他自己的 实例字段 x ,写成 具体对象名.字段名
//字段x是Test 类的对象变量,当然可以将他指向一个具体的 Test对象或者其子类的具体对象
x1.x=x2;x1=null;
x2=null;
}
}class test // 类名请用大写字母开头
{
test x; //声明了一个 Test 类型的对象变量,属于 Test 的实例字段,就是引用这个字段需要
//有具体对象的限定public test()
{}}我主要是不明白:这test x;定义了一个空句柄;
而在main方法里,用x2.x,x1.x这样用法,到底是个什么意思?
{
test x;
public test()
{}}
test只是test类的一个属性而已,无它。一般来说x2.x=x1;
x1.x=x2;
不是很常见,因为对对象属性的修改一般都是由类的方法来做的,如:class test
{
test x;
public test()
{}
void changeTest(){x=new test();}//此方法}
x2.x=x1,这条语句就是把对象x2中的x引用指向x1引用的对象,此时它x2中的x的值就不是null了,因为它指向了x1,尽管x1 好想是一个空的东西,但是它确实已经在内存中创建了一个这样的test对象。
{
test x;
public test()
{
}
}
public class Ex45
{
public static void main(String[]args)
{
test x1=new test();
test x2=new test();
x2.x=x1;
x1.x=x2;
//x1=null;
//x2=null;
System.out.println(x2.x);
System.out.println(x1.x);
}
}
//out:
D:\1>java Ex45
test@12498b5 //x1句柄的地址
test@1a5ab41 //x2句柄的地址
//
class test
{
test x;
public test()
{
}
}
public class Ex45
{
public static void main(String[]args)
{
test x1=new test();
test x2=new test();
x2.x=x1;
x1.x=x2;
x1=null;
//x2=null;
System.out.println(x2.x);
System.out.println(x1.x);
}
}
//out:D:\1>java Ex45
Exception in thread "main" java.lang.NullPointerException
at Ex45.main(Ex45.java:18)
说明x1=null,,是不能为null值的,,,