Site icon TestingDocs.com

Java Method Overloading

Overview

In this tutorial, we will learn Java method overloading. Overloaded methods have the same method name but different method signatures and implementations.

Java Method Overloading

Method overloading is allowing the programmer to define the same method name with different signatures and implementations. We say a method is overloaded when we provide different implementations of the method with the same method name. All the overloaded methods should be defined in the same class itself.

In Java, we can overload both static and non-static methods( instance methods)  within the same class.

Example

Let’s clear this with an example. In this example, add() method is overloaded to provide two different implementations.

public class MethodOverloadingDemo {
	public static void main(String[] args) {
		System.out.println(add(1,2));
		System.out.println(add("Hello ","World!"));

	}

	// add() method is overloaded 
	public static int add(int a,int b) {
		return a + b; //adds integers
	} 

	public static String add(String s1,String s2) {
		return s1.concat(s2); //concats strings
	} 
}

 

 

Constructors Overloading

Constructors of the class can also be overloaded. Constructors are special methods  that are invoked when the objects of the classes are created. Overloaded constructors allow developers to instantiate  objects of class in multiple ways.

Constructor method name has the same name as class name. For example, a Dog class can have multiple constructors as shown below:

 

	//default no-arg constructor
	public Dog() {
		this.name = "Default Name";
		this.weight = 1.0;
		this.height = 1.0;
	}
	
	//overloaded paramterized constructor
	public Dog(String name, double weight, double height) {
		this.name = name;
		this.weight = weight;
		this.height = height;
	}

 

 

Final methods

The final keyword for a method indicate that the method cannot be overridden in sub classes. They can be overloaded in the same class.

Example

public final void finalMethod() {
System.out.println(“Child classes cannot override ”
+ “this method”);
}

public final String finalMethod(String name) {
System.out.println(“Final methods can be”
+ “overloaded like this method”);
return “Hi, ” + name;
}

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version