Java Lab 2
Java Lab 2
Overloading:
Program:
import java.io.*;
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[])
{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));
System.out.println("add() with 3 parameters");
System.out.println(add(4, 6, 7));
}
}
Output:
add() with 2 parameters
10
add() with 3 parameters
17
Overriding:
Program:
import java.io.*;
class Animal {
void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}
class Dog extends Animal {
void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}
class MethodOverridingEx {
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();
d1.eat();
a1.eat();
Animal animal = new Dog();
animal.eat();
}
}
Output:
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.