Exercise 2
Write a class named Vehicle
Holds make and model (strings) and year (int)
Contains this method:
Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
Add getters and setters for each variable
Write a class called FordMustang that extends the Vehicle class
Create instance of object
Pass variables
Print
Please find the code for the following:
Code:
Vehicle.java:
//Write a class named Vehicle
public class Vehicle
{
//Created 3 variables to hold model, make and
year
protected String make;
protected String model;
protected int year;
//Constructor for the Vehicle class
Vehicle(String make, String model, int year)
{
this.make = make;
this.model = model;
this.year = year;
}
//getters and setters for each variable
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
FordMustang.java:
//Write a class called FordMustang that extends the Vehicle
class
public class FordMustang extends Vehicle
{
//This is for calling the constructor of the super
class which is Vehicle
FordMustang(String make, String model, int year)
{
super(make, model, year);
}
/*Main method*/
public static void main(String[] args)
{
//Create an instance of object and
pass the variables
FordMustang veh=new
FordMustang("Ford","GT 500",2001);
veh.setYear(2020);
//Print the variables
System.out.println(veh.getMake());
System.out.println(veh.getModel());
System.out.println(veh.getYear());
}
}
Please check the
compiled program and its output for your reference:
Output:
(I believe that I made the code simple and understandable. If you still have any query, Feel free to drop me a comment)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...
Get Answers For Free
Most questions answered within 1 hours.