Write a program with overloaded methods to print values.
Method overloading is the process where you write multiple methods in a class with same name but different number/type or parameters. When such an overloaded method is called, then the compiler selects the appropriate method depending on the number and type of arguments.
e.g.
class Number{
void printSquare(int n){
.....
}
void printSquare(double n){
......
}
}
The class above has two method with the same name printSquare(). Now if the we call
Number obj = new Number();
obj.printSquare(10);
we are calling the first method with integer parameter.
But if we call
obj.printSquare(1.56)
we are calling second method with double parameter.
Please remember that the overloading can not be done based only on return type of methods.
Here is our required class with two overloaded methods for printing the number.
Method overloading is the process where you write multiple methods in a class with same name but different number/type or parameters. When such an overloaded method is called, then the compiler selects the appropriate method depending on the number and type of arguments.
e.g.
class Number{
void printSquare(int n){
.....
}
void printSquare(double n){
......
}
}
The class above has two method with the same name printSquare(). Now if the we call
Number obj = new Number();
obj.printSquare(10);
we are calling the first method with integer parameter.
But if we call
obj.printSquare(1.56)
we are calling second method with double parameter.
Please remember that the overloading can not be done based only on return type of methods.
Here is our required class with two overloaded methods for printing the number.
public class OverloadedPrint{ void print(int num) { System.out.println("integer number is "+num); } void print(float num) { System.out.println("float number is "+num); } public static void main(String a[]) { OverloadedPrint obj = new OverloadedPrint(); obj.print(10); obj.print(1.2f); } }
Comments
Post a Comment