Java Method Overriding Example

In a Java class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. Method overriding can be used in the presence of Inheritance or Runtime Polymorphism.

Java decided at the runtime the actual method that should be called depending upon the type of object we create.  

Java Method Overriding Example

In this below example, the draw() method has overriding in respective subclasses.
class Shape {
    void draw() {
        System.out.println("drawing...");
    }
}
class Rectangle extends Shape {
    void draw() {
        System.out.println("drawing rectangle...");
    }
}
class Circle extends Shape {
    void draw() {
        System.out.println("drawing circle...");
    }
}
class Triangle extends Shape {
    void draw() {
        System.out.println("drawing triangle...");
    }
}
class TestPolymorphism2 {
    public static void main(String args[]) {
        Shape s;
        s = new Rectangle();
        s.draw();
        s = new Circle();
        s.draw();
        s = new Triangle();
        s.draw();
    }
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Here are the main rules that govern method overriding:
1. The name and signature of the method are the same in the superclass and subclass, or in the interface and its implementations.
2. We can't override a method in the same class (but we can overload it in the same class)
3. We can't override privatestatic, and final methods
4. The overriding method cannot reduce the accessibility of the overridden method, but the opposite is possible
5. The overriding method cannot throw checked exceptions that are higher in the exception hierarchy than the checked exception thrown by the overridden method
6. Always use the @Override annotation for the overriding method. 

Related Java OOPS Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments