In: Computer Science
Create a class called Car (Car.java). It should have the following private data members:
• String make
• String model
• int year
Provide the following methods:
• default constructor (set make and model to an empty string, and set year to 0)
• non-default constructor Car(String make, String model, int year)
• getters and setters for the three data members
• method print() prints the Car object’s information, formatted as follows:
Make: Toyota
Model: 4Runner
Year: 2010
public class Car {
}
Java Program :
public class Car
{
private String make, model; // declared all required variables as private
private int year;
Car() // default constructor to initialize all variables
{
make = "";
model = "";
year =0;
}
Car(String make, String model, int year) // Parameterized constructor to give values to variables
{
this.make = make; // this keyword is used to represent the class variable
this.model = model;
this.year = year;
}
void setMake(String make) // setter for make
{
this.make = make;
}
String getMake() // getter for make
{
return make;
}
void setModel(String model) // setter for model
{
this.model = model;
}
String getModel() // getter for model
{
return model;
}
void setYear(int year) // setter for year
{
this.year = year;
}
int getYear() // getter for year
{
return year;
}
void print() // prints all data
{
System.out.println("Make: "+make);
System.out.println("Model: "+model);
System.out.println("Year: "+year);
}
}
public class Main
{
public static void main(String[] args)
{
Car c = new Car("Toyota", "4Runner", 2010); // creates a new object of Class Car and intializes with a constructor
c.print(); // calls the print() method of Class Car
}
}
Screenshots / Outputs :