EXPERIMENT NO.
Date of Performance:
Date of Submission:
AIM: Programs on method and constructor overloading
THEORY:
Method Overloading:
Method overloading is a feature in Java that allows a class to define multiple methods with
the same
name but different parameter lists (type, number, or order of parameters).
It is an example of compile-time polymorphism, where the method to be executed is
determined at
compile time.
Key Points:
● Methods must differ in parameters.
● Return type can be same or different.
● Improves code readability and reusability.
Constructor Overloading:
Constructor overloading allows a class to have more than one constructor with different
parameter
lists. This enables different ways of initializing objects.
Key Points:
● All constructors must have the same name as the class.
● Each constructor must differ in number/type/order of parameters.
● Useful for setting default and custom values.
PROGRAM CODE:
[Link] Overloading:
class Calculator {
int substract(int a, int b) {
return a - b;
}
int substract(int x, int y, int z) {
return x - y - z;
}
double substract(double a, double b) {
return a - b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Difference(int, int): " + [Link](50, 40));
[Link]("Difference(int, int, int): " + [Link](100, 30, 40));
[Link]("Difference(double, double): " + [Link](30.5, 20.8));
}
}
ii . Constructor Overloading:
public class Person
{
// Declaring a non-parameterized constructor.
Person() {
[Link]("Introduction:");
}
// Declaring one parameterized constructor.
Person(String name){
[Link]("Name: " +name);
}
// Declaring two parameterized constructor.
Person(String clgname, int rollNo) {
[Link]("Clgname: "+clgname+ ", "+"Roll no:"+rollNo);
}
public static void main(String[] args)
{
// JVM will call constructor depending on arguments passed.
Person p1 = new Person(); // calling with zero argument.
Person p2 = new Person("Anuradha"); // calling with one argument.
Person p3 = new Person("Datta Meghe College of Engineering,19); // calling with two
arguments.
}
}
OUTPUT:
CONCLUSION:
Method and constructor overloading provide flexibility and enhance code maintainability.
They allow Java programs to use the same name for multiple operations or object
initializations, based on input parameters
SIGN AND REMARK:
R1 R2 R3 R4 Total Sign
(3 marks) (5 marks) (4 marks) (3 marks) (15 Marks)