Write a program to create a class named Vehicle having protected instance variables regnNumber, speed, color, ownerName and a method showData() to show "This is a vehicle class". Inherit the Vehicle class into subclasses named Bus and Car having individual private instance variables routeNumber in Bus and manufacturerName in Car and both of them having showData() method showing all details of Bus and Car respectively with content of the super class’s showData ( ) method.
public class Vehicles { protected String regnNumber, color, ownerName; protected int speed; MyOwnVehicles(String regno,String c,String owner,int sp) { regnNumber=regno; color=c; ownerName=owner; speed=sp; } public void showData() { System.out.println("This is a Vehicle Class"); } }
class Bus extends Vehicles { private int routeNumber; Bus(String regno, String c, String owner, int sp, int route) { super(regno, c, owner, sp); routeNumber = route; } public void showData() { super.showData(); System.out.println("Reg no: " + regnNumber); System.out.println("Color: " + color); System.out.println("Owner: " + ownerName); System.out.println("Speed: " + speed); System.out.println("Route: " + routeNumber); } }
class Car extends Vehicles { private String manufacturerName; Car(String regno, String c, String owner, int sp, String manu) { super(regno, c, owner, sp); manufacturerName= manu; } public void showData() { super.showData(); System.out.println("Reg no: " + regnNumber); System.out.println("Color: " + color); System.out.println("Owner: " + ownerName); System.out.println("Speed: " + speed); System.out.println("Manufacturer: " + manufacturerName); } }
import java.util.*; public class TestVehicle { public static void main(String[] args) { String regno,color,owner,manufacturer; int speed,route; //Bus Scanner sc=new Scanner(System.in); System.out.print("Eneter Bus Reg No : "); regno=sc.nextLine(); System.out.print("Eneter Bus color : "); color=sc.nextLine(); System.out.print("Eneter Bus Owner Name : "); owner=sc.nextLine(); System.out.print("Eneter Bus speed : "); speed=sc.nextInt(); System.out.print("Eneter Bus Route No : "); route=sc.nextInt(); Bus b = new Bus(regno,color,owner,speed,route); b.showData(); //Car System.out.print("Eneter Car Reg No : "); regno=sc.nextLine(); System.out.print("Eneter Car color : "); color=sc.nextLine(); System.out.print("Eneter Car Owner Name : "); owner=sc.nextLine(); System.out.print("Eneter Car speed : "); speed=sc.nextInt(); System.out.print("Eneter Car Manufacturer : "); manufacturer=sc.nextLine(); Car c = new Car(regno,color,owner,speed,manufacturer); c.showData(); } }