0% found this document useful (0 votes)
5 views3 pages

Java Lab 2

The document provides examples of method overloading and overriding in Java. It illustrates overloading with a program that defines multiple 'add' methods with different parameters, and overriding with a program where a 'Dog' class extends an 'Animal' class, demonstrating how the 'eat' method is redefined. Outputs for both examples are included to show the results of the method calls.

Uploaded by

g.dejasvini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Java Lab 2

The document provides examples of method overloading and overriding in Java. It illustrates overloading with a program that defines multiple 'add' methods with different parameters, and overriding with a program where a 'Dog' class extends an 'Animal' class, demonstrating how the 'eat' method is redefined. Outputs for both examples are included to show the results of the method calls.

Uploaded by

g.dejasvini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

2. Program to illustrate the use of overloading and overriding.

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.

You might also like