Advertisement
//Java - Example of method overloading
class Math
{
public void add(int a, int b) //add method adding two integers
{
System.out.println(a+b);
}
public void add(float a, float b) //add method adding two floats
{
System.out.println(a+b);
}
}
class Overload
{
public static void main(String... ar)
{
Math ob = new Math();
ob.add(1,2);
ob.add(2.5f,4.5f);
}
}
3
7.0
//Java - Example of method overloading
//A Math class with overloaded add methods, having different return types
class Math
{
public int add(int a, int b)
{
return(a+b);
}
public float add(float a, float b)
{
return(a+b);
}
}
class Overload
{
public static void main(String... ar)
{
Math ob = new Math();
System.out.println(ob.add(1,2));
System.out.println(ob.add(2.5f,4.5f));
}
}
3
7.0
//Java - Example of method overloading
class Rabbit
{
protected void eat() //eat method with protected access modifier
{
System.out.println("Rabbit eats carrots");
}
public void eat(String st) //eat method with public access modifier
{
System.out.println("Rabbit eats "+ st);
}
}
class Overload
{
public static void main(String... ar)
{
Rabbit ob= new Rabbit();
ob.eat();
ob.eat("grass");
}
}
Rabbit eats carrots
Rabbit eats grass
//Java - Example of method overloading
class A
{
public void greet() throws Exception
{
System.out.println("Hello!");
}
public void greet(String st)
{
System.out.println("Hello from " + st);
}
}
Advertisement
//Java - Example of method overloading through inheritance
class Sports //superclass
{
public void play() //original play() method with no arguments
{
System.out.println("Play any sport");
}
}
class Tennis extends Sports //subclass
{
public void play(String name) //overloaded play() method with String arguments
{
System.out.println("Play "+ name);
}
}
class Overload
{
public static void main(String... ar)
{
Tennis ob= new Tennis ();
ob.play();
ob.play("Tennis");
}
}
Play any sport
Play Tennis
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement