B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Java Method Overriding | Login Technologies

Method Overriding in Java

What is Method Overriding?

Method Overriding in Java allows a subclass to provide its own implementation of a method defined in the superclass.
It is used when a subclass wants to change or extend the behavior of the parent class method.

Java में Method Overriding का मतलब है कि subclass अपने superclass में defined method को अपने तरीके से implement कर सकता है।
जब subclass parent class के method का behavior बदलना या बढ़ाना चाहता है, तब overriding useful होती है।

Advantages of Method Overriding

  • Enables runtime (dynamic) polymorphism.
  • Allows subclass to provide specific implementation of a method.
  • Improves flexibility and code reusability.
  • Supports real-world hierarchies and specialization.
  • Runtime (dynamic) polymorphism को enable करता है।
  • Subclass को method का अपना version बनाने की अनुमति देता है।
  • Code को flexible और reusable बनाता है।
  • Real-world hierarchy और specialization को support करता है।

Example: Employee Class with Method Overriding

In this example, Manager class extends Employee and overrides the display() method to include department information.

इस उदाहरण में Manager class, Employee class को extend करती है और display() method को override करके department की जानकारी भी दिखाती है।

class Employee {
    String name;
    int id;

    Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("ID: " + id);
    }
}

class Manager extends Employee {
    String department;

    Manager(String name, int id, String department) {
        super(name, id);
        this.department = department;
    }

    @Override
    void display() {
        super.display();
        System.out.println("Department: " + department);
    }

    public static void main(String[] args) {
        Manager m = new Manager("Abhishek Gangwar", 101, "Sales");
        m.display();
    }
}

Output:

Name: Abhishek Gangwar
ID: 101
Department: Sales

In the example above, the Manager class overrides the display() method of the Employee class to add department details.

उपर के उदाहरण में Manager class ने Employee class के display() method को override किया है ताकि department की जानकारी भी दिखा सके।