Method Overloading

Method overloading is the same concept as constructor overloading. That is, you can use methods of the same name in the same class, but methods of the same name must have different types and numbers of parameters.

Method overloading allows you to implement polymorphism that provides a variety of implementations using a single interface that is characteristic of Java.

class Overload1 {
	void test() {
		System.out.println("No parameters");
	}

	void test(int a) {
		System.out.println("Parameters int" + a);
	}

	void test(int a, int b) {
		System.out.println("Parameters int " + a + "and int " + b);
	}

	void test(double a) {
		System.out.println("Parameters double " + a);
		return a * 2;
	}
}

class OverLoadDemo1 {
	public static void main(String args[]) {
		Overload1 ob = new Overload1();
		double result;

		ob.test();
		ob.test(100);
		ob.test(5, 10);
		result = ob.test(4.2);
		System.out.println("The result of ob.test(4.2) : " + result);
	}
}
Method Overloading Example 1
class Overload2 {
	void test() {
		System.out.println("No parameters");
	}

	void test(int a, int b) {
		System.out.println("Parameters int " + a + "and int " + b);
	}

	void test(double a) {
		System.out.println("Parameters double " + a);
		return a * 2;
	}
}

class OverLoadDemo1 {
	public static void main(String args[]) {
		Overload2 ob = new Overload2();
		int i = 88;

		ob.test();
		ob.test(10, 20);
		ob.test(i); //Execute void test(double a) through automatic type conversion
		ob.test(123.2);
	}
}
Method Overloading Example 2
class Overload {
	void calc() {
		System.out.println("No parameters");
	}

	void calc(int width) {
		system.out.println("The width of the square: " + width * width);
	}

	void calc(int width, int height) {
		system.out.println("The width of the rectangle: " + width * height);
	}

	void calc(int width, int height, int depth) {
		system.out.println("The volume of the rectangle: " + width * height + depth);
	}
}

class OverloadDemo3 {
	public static void main(String args[]) {
		Overload ol = new Overload();
		int input[] = new int[args.length];
		for(int i=0; i<args.length; i++) {
			input[i] = Integer.parseInt(args[i]);
		}
		switch(args.length) {
			case 0:
				ol.calc();
				break;
			case 1:
				ol.calc(input[0]);
				break;
			case 2:
				ol.calc(input[0], input[1]);
				break;
			case 3:
				ol.calc(input[0], input[1], input[2]);
				break;
			default:
				System.out.println("The number of arguments is high.");
		}
	}
}
Method Overloading Example 3

Leave a Reply

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

Latest Post