定义两个类
public class Cars {
private String carId;
private String coordinate;
public Cars(String carId, String coordinate)
{
this.carId=carId;
this.coordinate=coordinate;
}
}
public class Departments {
String name;
Cars cars;
public Departments( String name,Cars cars){
this.name=name;
???????????
cars该怎么来写呢? //如果成员变量为Cars类数组时,怎么来实现cars数组的初始化??
}
}
10 个解决方案
数组
public class Departments {
String name;
Cars[ ] carsArray;
public Departments( String name,Cars[ ] carsArray){
this.name = name;
this.carsArray = carsArray
}
}
实例化 Departments时传入carsArray即可,比如
将下面传入
Cars[ ] carsArray = { new Cars(xx,xx),new Cars(xx,xx)};
如果用this.cars=cars;的话,只是将cars的地址赋给了Departments里的cars,Department里的cars并没有申请内存。
当传入参数cars被系统销毁时,Departments里面的cars岂不是什么都没有了?怎么让Departments里的cars自己申请内存,并长久保留cars的信息?昨天试了用这种方法:
public class Departments {
String name;
Cars[ ] carsArray;
public Departments( String name,Cars[ ] carsArray){
this.name = name;
this.cars=new Cars;
}
}
编写了测试程序:如下
Cars cars=new Cars("AAAA","0000")
Departments dapertment=new Departments("AliBABA",cars);
cars.SetCarsname("BBBB");
将Departments中的cars.name输出,结果是BBBB!!!
这是为什么???
怎么让Departments里的cars长久保留cars的信息,不随传入的cars改变而改变?
this.cars = cars.clone();
你的类前后定义都变了。
你尝试这样吧
public class Cars {
private String carId;
private String coordinate;
public Cars(String carId, String coordinate)
{
this.carId=carId;
this.coordinate=coordinate;
}
}
public class Departments {
String name;
Cars cars;
public Departments( String name,Cars cars){
this.name=name;
this.cars = cars.clone();
}
}
谢谢!!!clone方法亲测有用!!!!!
还有一个疑问!!!!
public class Departments {
String name;
Cars cars;
public Departments( String name,Cars cars){
this.name=name;
this.cars=new Cars();//给cars分配存储空间!!!!!!!!这里明明给分配了存储空间呀!!!!
this.cars = cars;
}
}
我最初用的是上面这种方法来写构造器,但是在执行测试代码
Cars cars=new Cars("AAAA","0000");
Departments dapertment=new Departments("AliBABA",cars);
cars.SetCarsId("BBBB");
将Departments中的cars.carId输出,结果还是BBBB!!!
这表明
this.cars=new Cars();
这行代码没啥用啊!!!
问题:为什么这种方法不行,明明分配了新内存,
deparment里面的成员cars.carsId还是随着传入参数cars变化而变化!