2. Program to illustrate the use of overloading and overriding.
Overloading:
Program:
import [Link].*;
class MethodOverloadingEx {
static int add(int a, int b) { return a + b; }
static int add(int a, int b, int c)
{
return a + b + c;
}
public static void main(String args[])
{
[Link]("add() with 2 parameters");
[Link](add(4, 6));
[Link]("add() with 3 parameters");
[Link](add(4, 6, 7));
}
}
Output:
add() with 2 parameters
10
add() with 3 parameters
17
Overriding:
Program:
import [Link].*;
class Animal {
void eat()
{
[Link]("eat() method of base class");
[Link]("eating.");
}
}
class Dog extends Animal {
void eat()
{
[Link]("eat() method of derived class");
[Link]("Dog is eating.");
}
}
class MethodOverridingEx {
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();
[Link]();
[Link]();
Animal animal = new Dog();
[Link]();
}
}
Output:
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.