一个简朴的解决方案是交流成员。比方,假如类Car只要一个integer(整数)属性“no”(Car number),我们能够经由过程简朴地交流两辆车的成员来交流汽车。
class Car { int no; Car(int no) { this.no = no; } } class Main { public static void swap(Car c1, Car c2) { int temp = c1.no; c1.no = c2.no; c2.no = temp; } public static void main(String[] args) { Car c1 = new Car(1); Car c2 = new Car(2); swap(c1, c2); System.out.println("c1.no = " + c1.no); System.out.println("c2.no = " + c2.no); } }
输出:
c1.no = 2 c2.no = 1
假如我们不晓得Car的成员呢?
上面的解决方案是有用的,由于我们晓得Car中有一个成员“no”。假如我们不晓得Car的成员或许成员列表太大怎么办。这是一种异常罕见的状况,由于运用其他类的类能够无法访问其他类的成员。下面的解决方案有用吗?
class Car { int model, no; Car(int model, int no) { this.model = model; this.no = no; } void print() { System.out.println("no = " + no + ", model = " + model); } } class Main { public static void swap(Car c1, Car c2) { Car temp = c1; c1 = c2; c2 = temp; } public static void main(String[] args) { Car c1 = new Car(101, 1); Car c2 = new Car(202, 2); swap(c1, c2); c1.print(); c2.print(); } }
输出:
no = 1, model = 101 no = 2, model = 202
从上面的输出中我们能够看到,没有交流对象。参数在Java中是经由过程值通报的。因而,当我们将c1和c2通报给swap()时,swap()函数会建立这些援用的副本。
解决方案是运用Wrapper类假如我们建立一个包括Car援用的包装类,我们能够经由过程交流Wrapper类的援用来交流Car。
class Car { int model, no; Car(int model, int no) { this.model = model; this.no = no; } void print() { System.out.println("no = " + no + ", model = " + model); } } class CarWrapper { Car c; CarWrapper(Car c) {this.c = c;} } class Main { public static void swap(CarWrapper cw1, CarWrapper cw2) { Car temp = cw1.c; cw1.c = cw2.c; cw2.c = temp; } public static void main(String[] args) { Car c1 = new Car(101, 1); Car c2 = new Car(202, 2); CarWrapper cw1 = new CarWrapper(c1); CarWrapper cw2 = new CarWrapper(c2); swap(cw1, cw2); cw1.c.print(); cw2.c.print(); } }
输出:
no = 2, model = 202 no = 1, model = 101
因而,纵然user 类无法访问要交流对象的类的成员,Wrapper类解决方案依然有用。
相干引荐:《Java教程》
本篇文章就是关于Java交流对象的要领引见,愿望对须要的朋侪有所协助!
以上就是怎样在Java中交流对象数据?(代码实例)的细致内容,更多请关注ki4网别的相干文章!