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

  1. Create a same Method in the Child Class with the Same Method Name with the Super Class.
  2. Use the Child Class Method to override the Method in the Super Class or Parent Class.
  3. Method name in the Child Class  must have same name as in the parent class
  4. Method name in the Child Class  must have same parameter as in the parent class.
  5. Must be under Inheritance mode.

Class carPrice

  1. First i will create a class name ” carPrice ” .
  2. 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

  1. 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
  2. In order to inherit the Parent Class, or the Super Class“carPrice” I will need to use the extends Keyword.
  3. 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

 

  1. Finally i create a class i call it “whatThePrice” to access all the Class above.
  2. I create a new instance or object for the Class ” Mazda ” and “Citroen”
  3. 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