Method
overloading and type promotion
class Test {
void show(int a) {
System.out.println(“int method”);
}
void show(String a) {
System.out.println(“String method”);
}
public static void
main(String args[]) {
Test t= new Test();
t.show(a);
}
}
Automatic promotion:- one type of promoted to another implicitly if no matching data type is found.
Method overloading case1:
class Test {
void show(object a) {
System.out.println(“object method”);
}
void show(String a) {
System.out.println(“String method”);
}
public static void
main(String args[]) {
Test t= new Test();
t.show(“programming khata”);
}
}
Object is the parent class of all the classes in java.
Q.1 while resolving overloaded methods compiler will always give
precedence for the child type argument than compared with the parent type argument?
Case 3:-
class Test {
void show(object a) {
System.out.println(“object method”);
}
void show(int …
a) {
System.out.println(“verargs method”);
}
public static void
main(String args[]) {
Test t= new Test();
t.show(17);
t.show(17,34,78,66);
}
}
Case 4:-
class Test {
void show(String a,
float b) {
System.out.println(“string
float”);
}
void show(float a, int b)
{
System.out.println(“float int”);
}
public static void
main(String args[]) {
Test t= new Test();
t.show(“programming khata”,
17.76f);
t.show(16.54f, 56);
}
}
Case 5:-
class Test {
void show(StringBuffer a) {
System.out.println(“StringBuffer ”);
}
void show(String a) {
System.out.println(“string”);
}
public static void
main(String args[]) {
Test t= new Test();
t.show(“programming khata”);
t.show(StringBuffer(“programming
khata”) );
t.show(null);
}
}
The object of the parent class of all the classes in java
String and StringBuffer are at the same level so “null” cannot be if refer ambiguous error will occur.
In general verargs :- get least priority i.e if no other method matched, then only varargs method will get the chance because int come in 1.0 version and verargs come 1.5 version.
What is
verargs(verarguments) ?
Ø The verargs are always the method to accept zero or multiple arguments. Before varargs either we use the overloaded method or task an array as the method parameter but it was not considered good because it leads to the problem of maintenance. if we don’t know how many arguments we will have to pass in the method verargs is the better approach.
0 Comments