Write a class representing an Apartment with an Address (a string - e.g. \"123 m
ID: 3875809 • Letter: W
Question
Write a class representing an Apartment with an Address (a string - e.g. "123 main street"), Rent, Size (in square foot rounded off). Make sure these properties have error checking for their set method. Add a default constructor and a constructor that accepts values for each property. Add a ToString method. Add a property that returns the price per square foot. Include a main routine that tests all of your properties by setting a property with an allowable value then get the property and making sure it is the same value
Explanation / Answer
class Apartment {
// declaring variables
String address;
int rent;
int size;
double ppsqft;
// constructor without any values
Apartment(){
}
// constructor with values
Apartment(String ad, int re, int si)
{
address = ad;
if(rent > 0 && size > 0)
{
rent = re;
size = si;
// setting value of price per square foot also
ppsqft = rent / (size*1.0);
}
}
// getter for price per square foot
public double getPpsqft()
{
return ppsqft;
}
// method to put all properties in a string for description of it
public String toString()
{
return "Address : " + address + ", Rent : " + rent + ", size : " + size + ", price per square foot : " + getPpsqft();
}
// sample run
public static void Apartment(String[] args) {
// creating object with values
Apartment apart = new Apartment("123 main street", 1300, 200);
// using getter
System.out.println("Price per square foot: "+apart.getPpsqft());
// printing description
System.out.println(apart.toString());
}
}
/* SAMPLE OUTPUT
Price per square foot: 6.5
Address : 123 main street, Rent : 1300, size : 200, price per square foot : 6.5
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.