我试图弄清楚这是如何工作的。我知道这些方法存储在 java.lang.Object 中,但我不知道如何在代码中覆盖它们。这是我设计的一个小程序来测试我的理解(这是不对的)。
地址测试器:
import java.util.ArrayList;
import java.util.Scanner;
public class AddressTester
{
public static void main(String[] args)
{
Address home = new Address("123 Loving Fat Girl ln", "Dollywood", "NY",
"98765");
Scanner in = new Scanner(System.in);
System.out.println("-- Enter your home address --");
System.out.println("123 Loving Fat Girl ln, Dollywood, NY, 98765");
System.out.print("Enter the street address: ");
String addr = in.nextLine();
System.out.print("Enter the city: ");
String city = in.next();
System.out.print("Enter the state: ");
String state = in.next();
System.out.print("Enter the zipcode: ");
String zipcode = in.next();
Address enteredAddress = new Address(addr, city, state, zipcode);
System.out.println(enteredAddress);
if (home.equals(enteredAddress))
{
System.out.println("You are correct!");
}
else
{
System.out.println("You are incorrect!");
}
ArrayList<Address> addresses = new ArrayList<Address>();
addresses.add(home);
if (addresses.contains(enteredAddress))
{
System.out.println("The address wasn't found");
}
else
{
System.out.println("The address was found");
}
}
}
地址:
public class Address
{
private String address;
private String city;
private String state;
private String zipcode;
public Address(String address, String city, String state, String zipcode)
{
this.address = address;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
public boolean equals(Object otherObject)
{
if(otherObject == this)
{
return true;
}
if(otherObject != this)
{
return false;
}
return true;
}
public String getAddress()
{
return address;
}
public void setAddress(String addr)
{
this.address = addr;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getZipcode()
{
return zipcode;
}
public void setZipcode(String zipcode)
{
this.zipcode = zipcode;
}
}