Overriding vs Overloading in Java

Filed Under: Java
Overriding Vs Overloading In Java

Overriding Vs Overloading In Java

Overriding and Overloading are the core concepts in Java programming. They are the ways to implement polymorphism in our java programs. Polymorphism is one of the OOPS Concepts.

1. What is Overloading and Overriding?

When two or more methods in the same class have the same name but different parameters, it’s called Overloading.

When the method signature (name and parameters) are the same in the superclass and the child class, it’s called Overriding.

2. Overriding vs Overloading

  1. Overriding implements Runtime Polymorphism whereas Overloading implements Compile time polymorphism.
  2. The method Overriding occurs between superclass and subclass. Overloading occurs between the methods in the same class.
  3. Overriding methods have the same signature i.e. same name and method arguments. Overloaded method names are the same but the parameters are different.
  4. With Overloading, the method to call is determined at the compile-time. With overriding, the method call is determined at the runtime based on the object type.
  5. If overriding breaks, it can cause serious issues in our program because the effect will be visible at runtime. Whereas if overloading breaks, the compile-time error will come and it’s easy to fix.

3. Overloading and Overriding Example

Here is an example of overloading and overriding in a Java program.


package com.journaldev.examples;

import java.util.Arrays;

public class Processor {

	public void process(int i, int j) {
		System.out.printf("Processing two integers:%d, %d", i, j);
	}

	public void process(int[] ints) {
		System.out.println("Adding integer array:" + Arrays.toString(ints));
	}

	public void process(Object[] objs) {
		System.out.println("Adding integer array:" + Arrays.toString(objs));
	}
}

class MathProcessor extends Processor {

	@Override
	public void process(int i, int j) {
		System.out.println("Sum of integers is " + (i + j));
	}

	@Override
	public void process(int[] ints) {
		int sum = 0;
		for (int i : ints) {
			sum += i;
		}
		System.out.println("Sum of integer array elements is " + sum);
	}

}

The process() method is overloaded in the Processor class. Then, they are overridden in the child class MathProcessor.

Comments

  1. ranjit vamadevan says:

    hello,
    very happy with this website.

    1. Pankaj says:

      Thanks a lot for appreciation of our work.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages