Question
How can I override a method in an instantiated Java object?
class Parent {
void display() {
System.out.println("Parent Display");
}
}
class Child extends Parent {
@Override
void display() {
System.out.println("Child Display");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.display(); // This will call the overridden method in Child
}
}
Answer
In Java, method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. To override a method, the subclass must have the same method signature as the superclass method. This fundamental feature enables polymorphism in Java, allowing for dynamic method resolution at runtime.
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Calls Dog's sound method
}
}
Causes
- The method must be declared in the superclass.
- The subclass must use the @Override annotation for clarity and to prevent errors.
- The method signature (name and parameters) in the subclass must match the one in the superclass.
Solutions
- Define a superclass method that you intend to override.
- Create a subclass that extends the superclass.
- Use the same method name and parameters in the subclass method to implement the new functionality.
- Use the @Override annotation in the subclass method to indicate that you are overriding a method from the superclass.
Common Mistakes
Mistake: Not using the @Override annotation for the method in the subclass.
Solution: Always include the @Override annotation to help catch errors during compilation and improve code readability.
Mistake: Changing the method signature in the subclass.
Solution: Ensure that the method name and parameter types match exactly with the superclass method.
Mistake: Attempting to override a static method.
Solution: Remember that static methods cannot be overridden in the same way as instance methods; instead, they are hidden.
Helpers
- Java method overriding
- override method in Java
- Java subclass method
- Java polymorphism
- Java method example