Most of the Interview Room question what is varargs. Varargs method overriding, overloading.
Varargs : new concept came varargs with 1.5 version. varargs allows the method to multiple arguments. if you don't know how many parameter or argument will have to pass in the method, so varargs is better to use.
m1(int i){} we can call this method exactly one value
but
m1(int... i){} if I can take like we can call this method any by passing any value including 0 number...
so, you can take like obj.m1(10,20,30,40);
now, Overriding with varargs method. I'm using an example to explain overriding ,overloading varargs method.
class parentclass{
public void m1(int... i){
System.out.println("Parent");
}
}
class childclass extends parentclass{
public void m1(int i){
System.out.println("child");
}
}
public class MainClass{
public static void main(String agrs[]){
parentclass p = new parentclass();
p.m1(10);
childclass c = new childclass();
c.m1(10);
parentclass p1 = new childclass();
p1.m1(10);
}
}
output: parent,child,parent
in overriding method resolution always takes care by JVM based on the runtime object.so child method is the call. but here type is different. so this is overloading. A varargs method can be overridden with another varargs method. so, that is here is parent method is the call.
so now overriding
class parentclass{
public void m1(int... i){
System.out.println("Parent");
for(int x : i){
System.out.println(x);
}
}
}
class childclass extends parentclass{
public void m1(int... i){
System.out.println("child");
for(int x : i){
System.out.println(x);
}
}
}
public class MainClass{
public static void main(String agrs[]){
parentclass p = new parentclass();
p.m1(10,20,30,40);
childclass c = new childclass();
c.m1(10,20);
parentclass p1 = new childclass();
p1.m1(10,20,30,40);
}
}
output:
Parent
10
20
30
40
child
10
20
child
10
20
30
40
Comments
Post a Comment