Java overriding
Created By: chatGPT
In Java, method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This is a crucial aspect of polymorphism in object-oriented programming. When a method in a subclass has the same name, return type, and parameters as a method in the superclass, the subclass method overrides the superclass method.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Outputs: Dog barks
}
}
Important: When overriding a method, it's crucial to use the
@Override
annotation, which helps to ensure you are actually overriding a method from the superclass. If you mistakenly change the method signature, the compiler will generate an error if @Override
is used, helping you avoid bugs.class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows"); // Correctly overrides animal sound method
}
}
public class Example {
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.sound(); // Outputs: Cat meows
}
}
A method in a subclass can only override a method in a superclass if:
- The method in the superclass is not declared as final, static, or private.
- The overridden method must have the same return type or a subtype (covariant return type) in the subclass. The ability to override methods is a key feature of Java that promotes runtime polymorphism.
class Bird extends Animal {
@Override
void sound() {
System.out.println("Bird chirps");
}
}
public class Demo {
public static void main(String[] args) {
Animal myBird = new Bird();
myBird.sound(); // Outputs: Bird chirps
}
}