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.

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