Answer:
Check the explanation
Step-by-step explanation:
Car.java
//class Car
public class Car {
//private variable declarations
private int year;
private double price;
//getYear method
public int getYear() {
return year;
}
//setYear method
public void setYear(int year) throws CarException {
//check for the year is in the given range
if(year>=1970&&year<=2011)
this.year = year;
//else throw an exception of type CarException
else
throw new CarException("Invalid Year");
}
//getPrice method
public double getPrice() {
return price;
}
//setPrice method
public void setPrice(double price) throws CarException {
//check for the price is in the given range
if(price>=0&&price<=100000)
this.price = price;
//else throw an exception of type CarException
else
throw new CarException("Invalid Price");
}
//default constructor to set default values
public Car(){
this.year=1970;
this.price=0;
}
//overloaded constructor
public Car(int year, double price) {
//check for the year is in the given range
if(year>=1970&&year<=2011)
this.year = year;
//else initialize with default value
else
this.year=1970;
//check for the price is in the given range
if(price>=0&&price<=100000)
this.price = price;
//else initialize with default value
else
this.price=0;
}
//copy constructor
public Car(Car c){
this.year=c.year;
this.price=c.price;
}
//toString method in the given format
public String toString() {
return "[Year:" + year + ",Price:" + (int)price + "]";
}
//finalize method
public void finalize(){
System.out.println("The finalize method called.");
}
public static void main(String args[]) throws CarException{
Car a=new Car();
System.out.println(a.toString());
Car b=new Car(1986,25000.98);
System.out.println(b.toString());
Car c=new Car();
c.setYear(1900);
c.setPrice(23000);
System.out.println(c.toString());
Car d=new Car();
d.setYear(2000);
d.setPrice(320000);
System.out.println(d.toString());
}
}
CarException.java
//exception class declaration
public class CarException extends Exception{
//private variable declaration
private String message;
//constructor
public CarException(String message) {
super();
this.message = message;
}
//return error message
public String getMessage(){
return message;
}
}