200k views
1 vote
Implement a class Address. An address has a house number, a street, an optional apartment number, a city, a state, and a postal code. Supply two constructors: one with an apartment number and one without. Supply a print method that prints the address with the street on one line and the city, state, and postal code on the next line. Supply a method public boolean comesBefore (Address other) that tests whether this address comes before another when the addresses are compared by postal code.

1 Answer

5 votes

Answer:

public class Address {

//Class feilds

private int houseNumber;

private int apartmentNumber;

private String city;

private String state;

private int postalCode;

private String street;

// First Constructor with Apartment Number

public Address(int houseNumber, int apartmentNumber, String city, String state, int postalCode, String street) {

this.houseNumber = houseNumber;

this.apartmentNumber = apartmentNumber;

this.city = city;

this.state = state;

this.postalCode = postalCode;

this.street = street;

}

// Second Constructor without Apartment Number

public Address(int houseNumber, String city, String state, int postalCode, String street) {

this.houseNumber = houseNumber;

this.city = city;

this.state = state;

this.postalCode = postalCode;

this.street = street;

}

public void printMethod(Address other){

System.out.println("The street is "+other.street);

System.out.println(other.city+", "+other.state+", "+other.postalCode);

}

public boolean comesBefore (Address other){

if(other.postalCode > postalCode){

return false; //If the postal code is greater, it means it comes after

}

else return true;// the postal code is less, so it comes before

}

}

Step-by-step explanation:

  • This is implemented with Java language
  • The fields as described in the question are first created
  • The two constructors as specified follows
  • The method printMethod accepts an Address object as a parameter and prints the street on the first line then the city, state, and postal code on the next line
  • Finally the boolean method comesBefore receives an Address object as a parameter and compares the postalAdresses, if the postal address is greater, then the address comes after, else it comes before
User Wraf
by
2.8k points