Here's a class named "PrintIntegerChar" which
contains two methods with the same name "print()" but with different
sequence of the integer and character parameters:
Here is the code to implement the
scenario described
Source Code..
public class PrintIntegerChar {
// Method to print
an integer and a character
public void
print(int num, char ch) {
System.out.println("Integer:
" + num + ", Character: " + ch);
}
// Method to print
a character and an integer
public void
print(char ch, int num) {
System.out.println("Character: " + ch + ", Integer:
" + num);
}
// Main method to
test the class
public static void
main(String[] args) {
PrintIntegerChar obj = new PrintIntegerChar();
obj.print(10,
'A');
obj.print('B',
20);
}
}
Code Explanation:
In this code, we define a class named "PrintIntegerChar"
which contains two methods with the same name "print()" but with
different sequence of the integer and character parameters. The first method
takes an integer parameter followed by a character parameter, and the second
method takes a character parameter followed by an integer parameter.
To test the class, we create an object of the class and call
each method with different values. In the main method, we call
"print()" with an integer and a character parameter, and we also call
"print()" with a character and an integer parameter.
When we run the code, we should see the following output:
mathematica
Copy code
Integer: 10, Character: A
Character: B, Integer: 20
This example demonstrates how we can define multiple methods
with the same name but with different parameter sequence in Java using method
overloading. This allows us to write more concise and readable code by avoiding
the need to use different method names for similar functionality.
The concept used in this code is method overloading, which
allows us to define multiple methods with the same name but with different
parameters. In this case, we have two methods with the same name
"print()", but with different sequence of the integer and character
parameters. This makes the code more concise and readable, as we can use the
same method name for different functionality based on the parameter types and
sequence.
No comments:
Post a Comment