OOPS with Java Lab B.
Tech (AI/ML) || Sec- ‘E’
Experiment – 3
Object:- Write a java program for Method overloading and Constructor overloading.
Program:-
Method overloading:-
import java.io.*;
class MethodOverloading {
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(7, 3));
System.out.println("add() with 3 parameters");
System.out.println(add(7, 8, 5));
}
}
Output:-
6|Page Roll No:23012016400
OOPS with Java Lab B.Tech (AI/ML) || Sec- ‘E’
Constructor overloading:-
public class Student {
// Instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
// Object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(28, "Divyansh");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}
Output:-
7|Page Roll No:23012016400
OOPS with Java Lab B.Tech (AI/ML) || Sec- ‘E’
8|Page Roll No:23012016400