Overriding vs OverloadingΒΆ

Overriding an inherited method means providing a method in a child class with the same method signature (method name and parameter type list) and return type as a method in the parent class. The method in the child class will be called instead of the method in the parent class. In the following example the MeanGreeter inherits the greet method from Greeter, but then overrides it.

Note

To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method.

Overloading a method is when several methods have the same name but the parameter types, order, or number are different. In the example below the greet(String who) method overloads the greet() method of Greeter. Notice that MeanGreeter inherits this method and it isn’t overriden.

Note

To overload a method the method must have the same name, but the parameter list must be different in some way. It can have a different number of parameters, different types of parameters, and/or a different order for the parameter types. The return type can also be different.

Check your understanding

You can step through an example of this in the Java Visualizer by clicking on the following link Override Example.

You can step through an example of this using the Java Visualizer by clicking on the following link Overload Example.

What happens if you change the main method in the Java Visualizer to create a new Student object instead of a Person object? Does it still print the same thing?

Next Section - Using Super to call an Overridden Method