Method overloading and overriding java program

Method overloading and overriding java program

In this java program, we are going to see both method overloading and overriding examples.

Method overriding and overloading are two very important concepts in Java

Method overloading happens when two or more methods in one class have the same method name but parameters are different.

Method overriding happens when two methods with the same method name and parameters (method signature) in different classes which are having either parent and child inheritance relationships. Overriding provides a child class to define a specific implementation of a method that is already provided by its parent class.

Method overloading happens within the class and compile time polymorphism.

Method overloading happens based on multiple or two classes and run time polymorphism.

Sum is having add methods with different parameters, and overloading happens when calling add method using sum class object.

Sum and ExtendedSum classes are having multiple add methods with the same parameters, and overriding happens when calling add method using ExtendedSum class object.

import java.io.*;

class Sum 
{
	void add(int a, int b) {
		System.out.println("Two sum:" + (a + b)); 
	}
	void add(int a, int b, int c) {
		System.out.println("Three sums:" + (a + b + c));  
	}
}

class ExtendedSum extends Sum {
	void add(int a, int b){
		System.out.println ("Adding two:" + (a + b));
	}
	void add(int a, int b, int c) {
		System.out.println("Adding three:" + (a + b + c));  
	}
}

class Polymorphism {
	public static void main (String arcs []) {
		Sum s = new Sum();  
		System.out.println("Overloading & Overriding"); 
		s.add(10,5); 
		s.add(10,20,30); 
		ExtendedSum es = new ExtendedSum();  
		es.add(10,5);  
		es.add(10,20,30);
	}
}

Output:

Overloading & Overriding
Two sum:15
Three sums:60
Adding two:15
Adding three:60




Python installation

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^