Inheritance in Java
Inheritance in Java. In this Article i will explain what is inheritance Java programming by stepping through the sample program below
In the sample program below, first I will create a main class named “car ” . This main class will be inherited by the class which i will be creating call “toyota ” . Finally i will create a class call “createCar” to access both class.
Class Car
- First Declare a Variable for the car speed.
- Create a Constructor for for the Car Object
- Create the increase speed function
- Create the decrease speed function.
package Automation; public class car { // Car Engine Volume int engineVolume; int carSpeed; // create Object Constructor public car (int speed ){ carSpeed = speed; } // Create increase Speed Function public void increaseSpeed (){ carSpeed++; System.out.println("Increasing the Car Speed"); } public void decreaseSpeed (){ carSpeed--; System.out.println("Decreasing the Car Speed"); } }
Class toyota
- First I create a class call toyota.
- I use the extends word to inherit the car class
- Create a constructor for class toyota
- Using the Super word to access the car class function call“increaseSpeed ()”
- Use the @Overridekeyword to overwrite the information inside public void increaseSpeed () >
- Create a special function for class toyota
package Automation; // Toyota inherit the car characteristic public class toyota extends car { // Create a Constructor public toyota(int toyotaSpeed){ super(toyotaSpeed); } // Override the default Speed @Override public void increaseSpeed (){ System.out.println("Increasing Toyota Speed"); } public void specialFeature(){ System.out.println("Toyota Special Feature is less oil consumption"); } }
Class createCar
- First i declare a parameter ” speed” to be feed into the instance parameter later
- Then I create a new instance call ” firstCar “
- Then I called the newly created ” firstCar ” instance increaseSpeed() function
- I create a new instance called ” altis” for the toyota class
- Then i call the new altis instance function increaseSpeed() and specialFeature();function
- Finally the most important ever remember to import both class you have created
package Automation; import Automation.car; import Automation.toyota; public class createCar { public static void main(String[] args) { int speed =0; // Create a New Car Object car firstCar = new car(speed); firstCar.increaseSpeed(); // create a new toyota Model toyota altis = new toyota(speed); altis.increaseSpeed(); altis.specialFeature(); } }
Check out Java Oracle website hereIf you have any problem
Check out how to reverse element here