Java Programs: Classes, Objects, Method & Constructor Overloading
01. Programs on Classes and Objects in Java
1. Basic Program: Class and Object Example
------------------------------------------
class Student {
int id;
String name;
void display() {
[Link]("ID: " + id + ", Name: " + name);
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
[Link] = 1;
[Link] = "Alice";
[Link] = 2;
[Link] = "Bob";
[Link]();
[Link]();
Output:
ID: 1, Name: Alice
ID: 2, Name: Bob
2. Using Constructor in a Class
--------------------------------
class Employee {
int empId;
String empName;
Employee(int id, String name) {
empId = id;
empName = name;
void display() {
[Link]("Employee ID: " + empId + ", Name: " + empName);
}
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee(101, "John");
Employee e2 = new Employee(102, "Emma");
[Link]();
[Link]();
Output:
Employee ID: 101, Name: John
Employee ID: 102, Name: Emma
3. Class with Method Returning a Value
---------------------------------------
class Calculator {
int add(int a, int b) {
return a + b;
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
int result = [Link](5, 10);
[Link]("Sum: " + result);
Output:
Sum: 15
4. Class with Multiple Methods and Attributes
----------------------------------------------
class Circle {
double radius;
Circle(double r) {
radius = r;
double calculateArea() {
return 3.14159 * radius * radius;
double calculateCircumference() {
return 2 * 3.14159 * radius;
public class Main {
public static void main(String[] args) {
Circle c1 = new Circle(5);
[Link]("Area: " + [Link]());
[Link]("Circumference: " + [Link]());
Output:
Area: 78.53975
Circumference: 31.4159
02. Programs on Method and Constructor Overloading in Java
1. Program on Method Overloading
---------------------------------
class MathOperations {
int add(int a, int b) {
return a + b;
int add(int a, int b, int c) {
return a + b + c;
double add(double a, double b) {
return a + b;
}
public class Main {
public static void main(String[] args) {
MathOperations obj = new MathOperations();
[Link]("Sum of 2 integers: " + [Link](5, 10));
[Link]("Sum of 3 integers: " + [Link](5, 10, 15));
[Link]("Sum of 2 doubles: " + [Link](5.5, 10.5));
Output:
Sum of 2 integers: 15
Sum of 3 integers: 30
Sum of 2 doubles: 16.0
2. Program on Constructor Overloading
--------------------------------------
class Person {
String name;
int age;
Person() {
name = "Unknown";
age = 0;
}
Person(String n) {
name = n;
age = 0;
Person(String n, int a) {
name = n;
age = a;
void display() {
[Link]("Name: " + name + ", Age: " + age);
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("Alice");
Person p3 = new Person("Bob", 25);
[Link]();
[Link]();
[Link]();
}
Output:
Name: Unknown, Age: 0
Name: Alice, Age: 0
Name: Bob, Age: 25