方法能够返回任何类型的数据,包括你创建的类的类型。例如,在下面的程序中,incrbyten() 方法返回一个对象,在该对象中的值a比调用对象中的值a大10。
// returning an object.
class test {
int a;
test(int i) {
a = i;
}
test incrbyten() {
test temp = new test(a+10);
return temp;
}
}
class retob {
public static void main(string args[]) {
test ob1 = new test(2);
test ob2;
ob2 = ob1.incrbyten();
system.out.println("ob1.a: " + ob1.a);
system.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrbyten();
system.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
该程序产生的输出如下所示:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
正如你看到的,每次调用incrbyten() ,就产生一个新对象,同时将它的引用返回到调用子程序。
上面的程序还有另外重要的一点:既然所有的对象用关键字new动态地分配内存,你不必担心一个对象会出范围,因为它被其创建的方法终止。只要你程序中有它的一个引用,该对象将会继续存在。当没有该对象的引用时,在下一次垃圾回收发生时该对象将被回收。
闽公网安备 35060202000074号