我是 java 新手,第一次尝试使用组合。我构建了一个名为 Person 的类,它以字符串名称和对象 pAddress 作为属性。它有两个构造函数和一个复制构造函数,一个设置 PAAddress 属性的方法和一个 String toString 方法:
public class Person {
private String name;
private Address pAddress;
///*constructor that gets the city, street, number, zip from Address class*/
public Person (String name, String city, String street, int number, int zip)
{
this.name=name;
pAddress =new Address(city, street, number, zip);
}
public Person (String name, Address a)
{
this.name=name;
pAddress = new Address (a);
}
//**copy constructor**
public Person (Person other){
this.name=other.name;
this.pAddress= new Address (pAddress);}
//**set method for pAddress**
public void setPAddress(String city, String street, int number, int zip)
{
pAddress.setCity(city);
pAddress.setNumber(number);
pAddress.setStreet(street);
pAddress.setZip(zip);
}
**//String toString method**
public String toString(){
return this.name + ", " + pAddress;
}
但是,当我尝试打印 String toString 方法时,我得到对象部分的 NULL 值。更具体:
public static void main (String[]args){
Address Home=new Address("New York","5th Avenue", 112, 111);
Person a=new Person("Carl",Home);
System.out.println(a);
}
最后一个 println 出来了:
Carl, Address: nullst., 0, null
地址类如下所示:
public class Address {
private String city, street;
private int number, zip;
public Address (String c, String s, int n, int z){
city=c;
street=s;
number=n;
zip=z;
}
public Address (Address a)
{
this.city=city;
this.street=street;
this.number=number;
this.zip=zip;
}
public Address (String c, String s, int n)
{
zip=0;
city=c;
street=s;
number=n;
}
public String toString(){
if (zip==0)
return "Address: " + street + "st., " + number + ", " + city ;
return "Address: " + street + "st., " + number + ", " + city + ", " + zip;
}
我添加了一个比较对象内的值的方法:
public boolean sameAddress(Person p){
Person b=new Person (p.getName(), p.getPAddress());
if (p.getName()==name)
return true;
return false;
它应该检查 Person 的地址是否是两个对象的名称。
public static void main (String[]args){
Address Home=new Address("New York","5th Avenue", 112, 111);
Person a=new Person("Carl",Home);
Person b=new Person ("Carl",a.getPAddress());
System.out.println(b.sameAddress(a));
他们有相同的地址 我得到一个错误的答案 这里有什么问题?