Defining methods with the same name within the same class, but have a different number of parameters or same parameter with different datatypes are known as method overloading
Java uses the following aspects in order to call the correct method:-
1) Number of Arguments
2) Same Argument with different datatypes
However, the return type of a method isn’t sufficient to distinguish it from other versions. As a result, method overloading cannot be implemented using only the return type.
class showoverload{ void display(int x) { System.out.println("Hey I am display method with a single argument with integer type num = "+x); } void display(int x,int y) { System.out.println("Hey I am display method with a two argument of integer types num = "+x+", "+y); } void display(char c) { System.out.println("Hey I am display method with two argument of character type = "+c); } void display() { System.out.println("Hey I am display method with a no argument"); } } public class Overloading { public static void main(String[] args) { showoverload obj = new showoverload(); obj.display(10); obj.display(); obj.display('S'); obj.display(10,20); } }
Output:
When there is a method in subclass having the same name and type signature similar to its parent class with a specific implementation, it is said to be method overriding. Further, when an overridden method is called from the subclass, then Java always refers to subclass’s method, instead of its parent class’s method
class a{ void display() { System.out.println("Hi I m parent class"); } } class b extends a{ @Override void display() { System.out.println("Subclass is being called"); } } public class overrideMe{ public static void main(String[] args) { b obj = new b(); obj.display(); } }
Output:
This post was last modified on June 18, 2020