In: Computer Science
In Java, create an abstract vehicle class. Create a Truck Class
that Inherits from Vehicle Class. The vehicle class should contain
at least 2 variables that could pertain to ANY vehicle and two
methods. The truck class should contain 2 variables that only apply
to trucks and one method. Create a console program that will
instantiate a truck with provided member information then call one
method from the truck and one method contained from the inherited
vehicle class. Have these methods print something to the
console.
PROGRAM:
abstract class Vehicle //abstract class
{
String name;
String brand;
public abstract String getName(); //abstract method to
get name of vehicle
public abstract String getBrand(); //abstract method
to get brand of vehicle
}
class Truck extends Vehicle //truck class is inherited from
abstract vehicle class using extends keyword
{
int capacity; //capacity of truck
int noAxels; //number of wheels of truck
public Truck(int capacity,int noAxels,String
name,String brand) //parameterized constructoe to initialise
variables
{
this.capacity=capacity;
this.noAxels=noAxels;
super.name=name; // super keyword
is used to access parent class methods and variables
super.brand=brand; //setting brand
value
}
public String getName() // to get name of the
truck
{
return this.name;
}
public String getBrand() //to get brand of truck
{
return this.brand;
}
// to get the information of truck
public String toString() {
String str="Truck "+getName()+" has
"+this.noAxels+" Axels with capacity "+this.capacity;
return str;
}
public static void main(String args[]){
Vehicle v=new
Truck(10,4,"ABC","XYZ"); // truck class is instantiated by using
vehicle class
System.out.println("Truck name:
"+v.getName()); //print name of truck
System.out.println("Truck BRand:
"+v.getBrand()); //print bran of truck
System.out.println(v.toString());
//print truck information
}
}
OUTPUT: