提问人:MagicMan 提问时间:1/5/2022 更新时间:1/5/2022 访问量:311
使用引用从其他对象获取人员地址
Getting person addresses from other objects using the references
问:
通过引用从其他对象中检索地址。
您好,我正在为一项特定任务而苦苦挣扎。好吧,我有两门课要做,地址和人员数据(信息)。对于这两个类,我都创建了构造函数以及在屏幕上显示信息的选项。
地址类:
public class adres {
String postalCode;
String street;
String city;
public adres(String postalCode, String street, String city){
postalCode = postalCode;
street = street;
city = city;
System.out.println("Address: \n" + "Postal Code: " + postalCode + "\nStreet: " + street + "\nCity: " + city + "\n --------------------------------- \n");
}
}
人员等级:
public class person {
String name;
String surname;
int phone_number;
public person(String name, String surname, int phone_number){
name = name;
surname = surname;
phone_number = phone_number;
System.out.println("Client data:\n" + "name and surname: " + name + " " + surname + "\n" +"Phone number: " + phone_number + "\n");
}
}
在主文件中,我包含对象,这些对象后来使用构造函数进行初始化。起始文件代码如下所示:
public class starter {
public static void main(String[] args) {
String name1 = "John";
String surname1 = "Bush";
int phone_number1 = 575332114;
person data1 = new person(name1,surname1,phone_number1);
String postalCode = "47-321";
String street = "Washington St.";
String city = "Washington";
adres info1 = new adres(postalCode,street,city);
//-------------------------------------------------------------------
String name2 = "George";
String surname2 = "Denis";
int phone_number2 = 338729416;
person data2 = new person(name2,surname2,phone_number2);
adres info2 = info1;
info2 = new adres(postalCode,street,city);
//-------------------------------------------------------------------
String name3 = "Tom";
String surname3 = "Rolling";
int phone_number3 = 165776879;
person data3 = new person(name3,surname3,phone_number3);
String postalCode2 = "17-221";
String street2 = "Green St.";
String city2 = "York";
adres info3 = new adres(postalCode2,street2,city2);
//-------------------------------------------------------------------
String name4 = "Eric";
String surname4 = "Murble";
int phone_number4 = 335757449;
person data4 = new person(name4,surname4,phone_number4);
adres info4 = info3;
info4 = new adres(postalCode2,street2,city2);
}
}
对于我使用参考资料分配的先前地址的两个人。这个想法是:如果地址是从另一个对象(并且它已经存在)获取的,那么通过引用从该对象分配值。我做对了吗?代码编译正确,但我想知道如何改进它以及当前解决方案有什么缺点(例如,其中之一肯定是缺少条件指令,但我不应该使用它们)。
有没有人能够证实我的推理 - 引用应该像我在代码中呈现的那样吗?提前感谢您的帮助!
答: 暂无答案
评论
Person
adres
adres info2 = info1;
info2
Person
Address
Person
Address
Person
Address anAdress = new Address(...); Person person1 = new Address(..., anAddress); Person person2 = new Address(..., anAddress);
person1
person2
Address