Method Overriding in Java


Overriding in Inheritance is used when you use a already defined method from a super class in a sub class, but in a different way than how the method was originally designed in the super class. Overriding allows the user to reuse code by using existing material and modifying it to suit the user’s needs better.

  • The user class is the base or parent class that contains two instance variables - name and age, along with a constructor to initialize these variables and a display method to print the values of these variables.
  • The MainProgrammer class is a derived or child class that extends the user class. This class has an additional instance variable CompanyName and its own constructor that calls the constructor of the parent class using the super keyword. This class also has its own implementation of the display method that first calls the display method of the parent class using the super keyword and then adds its own code to display the value of the CompanyName variable.
  • The methodOverriding class contains the main method that creates an object of the MainProgrammer class and calls its display method to print the values of all three instance variables.
  • When the display method of the MainProgrammer class is called, it overrides the implementation of the display method in the user class and displays the values of all three instance variables (name, age, and CompanyName) in the order specified by its own implementation. This is an example of method overriding in Java.

Source Code

//Method Overriding in Java
class user { //Base
    String name;
    int age;
    user(String n, int a) {
        this.name = n;
        this.age = a;
    }
    public void display(){
        System.out.println("Name  : "+name);
        System.out.println("Age   : "+age);
    }
 
}
class MainProgrammer extends user{ //Derived Class
    String CompanyName;
    MainProgrammer(String n, int a,String c){
        super(n,a);
        this.CompanyName=c;
    }
    public void display(){
        System.out.println("Name  : "+name);
        System.out.println("Age   : "+age);
        System.out.println("Company Name : "+CompanyName);
    }
 
}
public class methodOverriding {
    public static void main(String args[]) {
        MainProgrammer o =new MainProgrammer("Raja",22,"Tutor Joes");
        o.display();
    }
}
 

Output

Name  : Raja
Age   : 22
Company Name : Tutor Joes
To download raw file Click Here

Basic Programs