DEV Community

Sundar Joseph
Sundar Joseph

Posted on

Overriding in Java

Overriding in Java occurs when a subclass or child class implements a method that is already defined in the superclass or base class. When a subclass provides its own version of a method that is already defined in its superclass, we call it method overriding. The subclass method must match the parent class method's name, parameters, and return type.

Rules for Overriding:

Name, parameters, and return type must match the parent method.
Java picks which method to run, based on the actual object type, not just the variable type.
Static methods cannot be overridden.
The @override annotation catches mistakes like typos in method names.

Example :

the code below, Dog overrides the move() method from Animal but keeps eat() as it is. When we call move() on a Dog object, it runs the dog-specific version.
// Example of Overriding in Java
class Animal {
// Base class
void move() { System.out.println(
"Animal is moving."); }
void eat() { System.out.println(
"Animal is eating."); }
}

class Dog extends Animal {
@override void move()
{ // move method from Base class is overriden in this
// method
System.out.println("Dog is running.");
}
void bark() { System.out.println("Dog is barking."); }
}

public class Geeks {
public static void main(String[] args)
{
Dog d = new Dog();
d.move(); // Output: Dog is running.
d.eat(); // Output: Animal is eating.
d.bark(); // Output: Dog is barking.
}
}

Output ;

Dog is running.
Animal is eating.
Dog is barking.

Top comments (0)