27 June 2023

Method Overloading In Java - learngreen.net

 Method overloading in Java lets in you to define a couple of methods in a class with the same title however different parameter lists. It helps you operate similar duties with one-of-a-kind types of inputs. When you call an overloaded method, Java determines which model of the method to execute based totally on the parameters you pass. This makes your code more flexible, readable, and avoids the need to come up with special names for similar operations.


Method Overloading In Java






 //Example1
 package Interview;
 
 public class MyClass {
 //Method to convert a String value to an int
 public int Change (String Value){
 return Integer.parseInt(Value);
	 }
 //Method that returns a double value as it is
 public double Change(double value){
 return value; 
 }
 public static void main (String[] args){
 // Create an object of MyClass	 
 MyClass obj = new MyClass();
 //Call the change method with string argument
 int num = obj.Change("58");
 //Call the change method with double argument
 double decimal = obj.Change(3.14);

 System.out.println(num);
 //Output-> 58
 System.out.println(decimal);
 //Output-> 3.14
	}
 }

 



//Example 2
package Interview;
 
 public class MyClass {
 //create method to divide integers	 
 public int divide (int r, int s) {
 return r/s;
 }
 //create method to divide doubles
 public double divide (double r, double s) {
 return r/s;	 
 }

 public static void main (String[] args){
 //create an object of MyClass	 
 MyClass obj = new MyClass();
 //call the divide method with integers &
 //store the result in division1
 int division1 = obj.divide(8, 2);
 System.out.println(division1);
 //output-> 4
 
 //call the divide method with doubles &
 //store the result in division2
 double division2 = obj.divide(5.5,2.5);
 System.out.println(division2);
 //output-> 2.2
	}
 }

 


 //Example 3

 package Interview;
 
 public class MyClass {
 public void print(String expression ) {
 //create method print with parameter string	
 System.out.println(expression);	 
 }
 public void print(int digit) {
 //create method print with parameter digit	 
 System.out.println(digit);
 }
 public void print(boolean flag) {
 //create method print with boolean parameter
 System.out.println(flag);
 }
 public static void main (String[] args){
 MyClass obj = new MyClass();
 obj.print("Save Water");
 //Output-> Save Water
 obj.print(84);
 //Output-> 84
 obj.print(true);
 //Output-> true
	}
 }

 



No comments:

Post a Comment