Overriding in Java
Overriding in Java!. In this Article i will explain what is an overriding in Java by stepping through the sample program below
In the sample program below, first I will create a super class named “carPrice” .Then i will create “2 child “class the same Method name , to overwrite the Parent Method in the Super Class.
Finally i will create a class i named it “whatThePrice” ,to access the Super Class, and both Child Class
Things to take Note about Overriding in Java
- Create a same Method in the Child Class with the Same Method Name with the Super Class.
- Use the Child Class Method to override the Method in the Super Class or Parent Class.
- Method name in the Child Class must have same name as in the parent class
- Method name in the Child Class must have same parameter as in the parent class.
- Must be under Inheritance mode.
Class carPrice
- First i will create a class name ” carPrice ” .
- Inside the ” carPrice ” i will create a method i named it “theCarPrice()” this method will be Override by the Child Class later .
package auto; public class carPrice { public void theCarPrice(){ System.out.println("The Price of this Car is $ 20000"); } }
Class mazda
- Now i will create 2 classes i called it Mazda and Citroen,I will use this method inside both of this classes to override the Super Class or Parent Class Method
- In order to inherit the Parent Class, or the Super Class“carPrice” I will need to use the extends Keyword.
- Then i create a method both of the child class with the Same method name to the Super Class, but with different output Parameters
package auto; public class mazda extends carPrice { public void theCarPrice(){ System.out.println("The Price of this Car is $ 25000"); } }
package auto; public class citroen extends carPrice { public void theCarPrice(){ System.out.println("The Price of this Car is $ 35000"); } }
Class whatThePrice
- Finally i create a class i call it “whatThePrice” to access all the Class above.
- I create a new instance or object for the Class ” Mazda ” and “Citroen”
- Access the Chid Class ” Mazda ” and “Citroen ” method through the Instance that i have just created
package auto; public class whatThePrice { public static void main(String[] args) { mazda typeOne = new mazda(); citroen euroCar = new citroen(); typeOne.theCarPrice(); euroCar.theCarPrice(); } }
Check out Method Overload in Java here
Leave a Reply