This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Method overloading interview questions java
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Method is a sub block of a class that contains logic of that class.
logic must be placed inside a method, not directly at class level, if we place logic at class level compiler throws an error.
So class level we are allowed to place variables and methods.
The logical statements such as method calls, calculations and printing related statements must be placed inside method, because these statements are considered as logic.
System.out.println("instance of java"); // compiler throws an error.
}
package com.instanceofjava;
class sample{
static int a=10;
public static void main(String args[]){
System.out.println(a); // works fine,prints a value:10
}
}
2.What is meant by method overloading in java?
Defining multiple methods with same name is known as polymorphism.
Defining multiple methods with same name and with different arguments known as method overloading.
package com.instanceofjava;
class A{
public void show(int a){
System.out.println("saidesh");
}
public void show(int a,int b){
System.out.println("ajay");
}
public void show(float a){
System.out.println("vinod");
}
public static void main(String args[]){
A a=new A();
a.show(10);
a.show(1,2);
a.show(1.2);
}
}
Output:
saidesh
ajay
vinod
3.What are the other names for method overloading?
Method overloading also known as static polymorphism or compile time polymorphism because at compile time itself we can tell which method going to get executed based on method arguments.
So method overloading also called as static binding.
4.What are the basic rules of method overloading?
Defining a method with same name and differ in number of arguments
Defining a method with same name and differ in type of arguments
Defining a method with same name and differ in order of type of arguments
Return type of the method not involved in method overloading.
5.Can we overload static methods in java?
Yes. We can overload static methods in java.
Method overriding is not possible but method overloading is possible for static methods.
Before that lets see about method overloading in java.
lets see an example java program which explains static method overloading.
class StaticMethodOverloading{
public static void staticMethod(){
System.out.println("staticMethod(): Zero arguments");
}
public static void staticMethod(int a){
System.out.println("staticMethod(int a): one argument");
}
public static void staticMethod(String str, int x){
System.out.println("staticMethod(String str, int x): two arguments");