Inheritance allows a new class to be based on an existing class. The news class inherits the members of the class it is based on.
A rectangle is a shape
A circle is a shapes
How we can use Inheritance?
For our example, we are going to have two subclasses(electric cars, diesel cars) and a parent class(class). Our two subclasses are going to inherit from our parent class.
First lets code our parent class:
import java.lang.*;
class Cars{
private String carColor;
private int maxSpeed;
private int buildYear;
private String carModel;
public Cars(String carColor, int maxSpeed, int buildYear, String carModel){
this.carColor = carColor;
this.buildYear = buildYear;
this.carModel = carModel;
this.maxSpeed = maxSpeed;
}
public String getCarColor() {
return carColor;
}
public void setCarColor(String carColor) {
this.carColor = carColor;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public void setBuildYear(int buildYear) {
this.buildYear = buildYear;
}
public void setCarModel(String carModel) {
this.carModel = carModel;
}
@Override
public String toString(){
return ("Car color: " + carColor + "\nBuild year: " + buildYear + "\nMax Speed: " + maxSpeed + "-MPH" + "\nCar Model: " + carModel );
}
}
Now it is time to code our two subclasses. First let's code our Diesel Cars class:
class DieselCars extends Cars{ private int milesPerGallon;
public DieselCars(String carColor, int maxSpeed, int buildYear, String carModel, int milesPerGallon) {
super(carColor, maxSpeed, buildYear, carModel);
this.milesPerGallon = milesPerGallon;
}
public void setMilesPerGallon(int milesPerGallon) {
this.milesPerGallon = milesPerGallon;
}
public String toString(){ return (super.toString()+ "\nMiles Per Gallon: " + milesPerGallon); }}
Second, let's code our Electric Cars class:
class ElectricCars extends Cars{
private int milesPerCharge;
public ElectricCars(String carColor, int maxSpeed, int buildYear, String carModel, int milesPerCharge) {
super(carColor, maxSpeed, buildYear, carModel);
this.milesPerCharge = milesPerCharge;
}
public void setMilesPerCharge(int milesPerCharge) {
this.milesPerCharge = milesPerCharge;
}
public String toString(){
return (super.toString()+ "\nMiles Per Charge: " + milesPerCharge);
}
}
Time to test our code:
class TestClass{
public static void main(String [] args){
DieselCars myCar = new DieselCars("Red",182,1992,"Ford Mustang", 150);
ElectricCars myECAR = new ElectricCars("Silver", 220, 2017, "Tesla", 250);
System.out.println(myCar.toString());
System.out.println("");
System.out.println(myECAR.toString());
/*MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());*/
}
}
Output:
Car color: Red
Build year: 1992
Max Speed: 182-MPH
Car Model: Ford Mustang
Miles Per Gallon: 150
Car color: Silver
Build year: 2017
Max Speed: 220-MPH
Car Model: Tesla
Miles Per Charge: 250
No comments:
Post a Comment