In: Computer Science
Create a class called Vehicle that includes four instance variables:
name, type,
tank size and average petrol consumption.
If tank size and average petrol consumption are not given, then return:
Vehicle [name=”Corolla”, type=”Sedan” ]
Otherwise its returned value:
Vehicle [name=”Corolla”, type=”Sedan”, tank Size=50.00 liters, average petrol consumption =22.00 liter/KM, can cross 1100.00 per tank]
(3 pt)
Running example:
Vehicle [name=”Corolla”, type=”Sedan” ]
Vehicle [name=”A5”, type=”Coupe” ]
Vehicle [name=”Mustange”, type=”Sport”, tank Size=60.00 liters, average petrol consumption =8.00 liter/KM, can cross 480.00 per tank ]
Vehicle [name=”Civic”, type=”Sedan”, tank Size=47.00 liters, average petrol consumption =15.00 liter/KM, can cross 705.00 per tank ]
code:
public class Main_vehicle
{
public static void main(String[] args) {
Vehicle ob = new Vehicle("Corolla","Sedan");
System.out.println(ob);
Vehicle ob1 = new Vehicle("A5","Coupe");
System.out.println(ob1);
Vehicle ob2 = new
Vehicle("Mustange","Sport",60,8);
System.out.println(ob2);
Vehicle ob3 = new
Vehicle("Civic","Sedan",47,15);
System.out.println(ob3);
}
}
class Vehicle
{
String name;
String type;
double tank_size=0;
double avg_petrol_consumption=0;
public Vehicle(String name, String type)
{
this.name = name;
this.type = type;
}
public Vehicle(String name, String type, double
tank_size, double avg_petrol_consumption)
{
this.name = name;
this.type = type;
this.tank_size =
tank_size;
this.avg_petrol_consumption = avg_petrol_consumption;
}
double distancePerTank()
{
return
tank_size*avg_petrol_consumption;
}
public String toString()
{
if((tank_size!=0)&&(avg_petrol_consumption!=0))
{
return "Vehicle [name=\""+name+"\", type=\""+type+"\", tank
Size="+tank_size+" liters, average petrol consumption
="+avg_petrol_consumption+" liter/KM, can cross
"+distancePerTank()+" per tank]";
}
else
{
return "Vehicle [name=\""+name+"\", type=\""+type+"\"]";
}
}
}
output: