Polymorphism in Java: How to Overload or Override Methods

Method overloading and overriding are the two ways in which Java demonstrates polymorphism. Polymorphism comes from a combination of two Greek words: “poly” meaning many and “morph” meaning form. Therefore, polymorphism enables methods to take on many forms.

Follow this guide to learn how to overload or override methods in Java.

What Is Method Overloading?

“Method overloading” refers to defining different methods in a class with the same name. The methods must have different signatures. A method signature is the combination of a method’s name and parameter list. It doesn’t include the return type.

The compiler knows which method to use by checking the type, number of parameters, and order in which they are placed.

Related: Exploring Inheritance in the Java Programming Language

Method overloading demonstrates compile-time polymorphism. Compile-time polymorphism means that the Java compiler binds an object to its functionality at runtime. The compiler checks method signatures to achieve this.

This type of polymorphism is also known as static or early binding.

See the method overloading example below:

class Arithmetic{
int cube(int x){
return x*x*x;
}
double cube(double x){
return x*x*x;
}
float cube(float x){
return x*x*x;
}
public static void main(String[] args){
Arithmetic myMultiplication = new Arithmetic();
System.out.println("The cube of 5 is " + myMultiplication.cube(5));
System.out.println("The cube of 5.0 is " + myMultiplication.cube(5.0));
System.out.println("The cube of 0.5 is " + myMultiplication.cube(0.5));
}
}

Output:

The cube of 5 is 125
The cube of 5.0 is 125.0
The cube of 0.5 is 0.125

The code above shows how you can get a cube of different types (int, double, float) using the same method.

Generally, method overloading is used to define similar methods with different parameter types.

What Is Method Overriding?

This refers to a different implementation of a method in a subclass. The method must have already been defined in the parent class.

The overriding method (i.e. the one in the subclass) must have the same method signature as that in the superclass. The return type of the overriding method may be the same or a subtype of the one in the superclass.

Overriding is generally used to include a specific implementation of an object’s behavior in the subclass.

class Account{
public void message() {
System.out.println("
Thank you for opening an account with us!");
}
public static void main(String args[]) {
Account myAccount = new Account();
Savings mySavings = new Savings();
FixedDeposit myFixedDepo = new FixedDeposit();
myAccount.message();
mySavings.message();
myFixedDepo.message();
}
}
class Savings extends Account {
public void message() {
System.out.println("
Thank you for opening a Savings account with us!");
}
}
class FixedDeposit extends Account {
public void message() {
System.out.println("
Thank you for opening a Fixed Deposit account with us!");
}
}

Output:

Thank you for opening an account with us!
Thank you for opening a Savings account with us!
Thank you for opening a Fixed Deposit account with us!

The above example shows how the method message() is overridden in the subclasses Savings and FixedDeposit. Different messages will be displayed for bank account holders with a Savings account and those with a Fixed Deposit account.

Related: What You Need to Know About Using Strings in Java

It’s also worth noting that method overriding demonstrates runtime polymorphism or dynamic method dispatch. This means that the method to be called is resolved at runtime rather than at compilation.

To avoid a method from being overridden, use the keyword final.

final void message (){
System.out.println("
Thank you for opening an account with us!");
}

When a subclass attempts to override it, a compilation error will occur.

Ideally, all methods called within a constructor should be final. This is to avoid any unintended changes that may be caused by the subclasses.

Sometimes, you may need to access an overridden method within the overriding method. You can use the keyword super followed by the dot operator (.) and the method name in such a case.

Consider the superclass Animal.

class Animal{
public void move() {
System.out.println("
I can move.");
}
}

Below is a subclass, called Fish, that overrides move():

class Fish extends Animal {
public void move() {
System.out.println("
I can swim.");
super.move();
}
public static void main(String args[]){
Fish Tilapia = new Fish();
Tilapia.move();
}
}

Output:

I can swim.
I can move.

When overriding a method, you also need to be mindful of the access modifier used. The modifier in the subclass should have the same level of visibility or higher than in the base class. For example, if the method in the base class is defined as protected, then the overriding method can either be protected or public.

Simple Code With Polymorphism

Method overriding and overloading are important for code simplification, and simple code is good practice.

Why? Imagine a complex codebase with more ins and outs than than Grand Central Station. Now imagine a devastating bug begins to destroy your hard work before your very eyes. You need to isolate the source of the infection, and you need to do it quickly.

Good luck, you didn’t simplify your code… Now you’re about to get a true lesson in cryptography. Employing effective data structures and doing what you can to shorten code (such as keeping DRY in mind) is your best defense against a situation like this.

Next up on your Java learning list should be working with arrays. They’re important data structures used to store batches of data points.

Source: makeuseof.com

Related posts

Soundbar vs. AV Receiver: What’s Best for Your Home?

How to Find Hidden Tracking Devices With Apple and Google’s Detection Tool

Here’s How I Prevent Screen Burn-In on My OLED Monitor and TV