Overriding and Overloading Method

Overriding Method     Overloading Method

A child class can override parent’s instance method with the same name, parameters, and return type.

Multiple methods with the same name and return type, but different parameters.

Polymorphism
The definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms. This principle can also be applied to object-oriented programming like the Java language, for example with overriding and overloading method.

Overriding Method
Subclass can override method inherit from a superclass and modify its behavior as needed.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If the compiler detects that the method does not exist in one of the superclasses, it will generate an error.

public class Student {
    public void wearUniform() {
        System.out.println("The student wear white uniform.");
    }
}
   
public class HighSchoolStudent extends Student {
    @Override
    public void wearUniform() {
        System.out.println("The high school student wear blue uniform.");
    }
}

Overloading Method
Overloading allows the same method name to perform different actions depending on parameters.
Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method.

public class Student {
    public void submitHomework(String subject) {
        System.out.println("The student submit homework: " + subject);
    }
   
    public void submitHomework(String subject, String teacherName) {
        System.out.println("The student submit homework: " + subject + " to teacher: " + teacherName);
    }
   
    public void submitHomework(String subject, Calendar dueDate) {
        System.out.println("The student submit homework: " + subject + " before: " + dueDate.DAY_OF_MONTH + " " + dueDate.MONTH + " " + dueDate.YEAR);
    }
}

 

References :

 

Leave a comment