Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
113 views
in JAVA by (178k points)
What is method overriding in Java inheritance?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

Method overriding is a feature of Java inheritance that allows a subclass to provide its own implementation of a method that is already defined in its superclass.

When a subclass overrides a method, it provides a new implementation of that method, which replaces the implementation inherited from the superclass. The new implementation in the subclass must have the same method signature (name, return type, and parameter list) as the method being overridden in the superclass.

Here's an example of method overriding in Java:

class Animal {
    void makeSound() {
        System.out.println("The animal makes a sound.");
    }
}

class Cat extends Animal {
    void makeSound() {
        System.out.println("The cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound(); // Output: "The animal makes a sound."
        
        Cat myCat = new Cat();
        myCat.makeSound(); // Output: "The cat meows."
    }
}
 

In this example, the Animal class has a makeSound() method that simply prints out a message. The Cat class extends the Animal class and overrides the makeSound() method with its own implementation that prints out "The cat meows."

When the makeSound() method is called on an instance of the Animal class, the output is "The animal makes a sound." However, when the same method is called on an instance of the Cat class, the output is "The cat meows." This is because the Cat class has provided its own implementation of the makeSound() method, which overrides the implementation inherited from the Animal class.

Related questions

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...