UNIT 2
OBJECT OREINTED PROGRAMMING
2.a Implementation of Constructors
Ex. 2.a1 - Implementation of Constructor Initialization
Aim :
The 'Cabservice' is an organisation that provides 'Online Booking' for the
passengers to avail pick- up and drop facility. Create a program by initializing the
constructor.
Algorithm:
Step 1. Define a class Cabservice with attributes: taxino, name, d, amt.
Step 2. Create a constructor Cabservice that initializes the attributes with default
values.
Step 3. Define a method input that:
• Creates a Scanner object to read input from the user
• Prompts the user to enter: taxino, name, d(distance travelled) and Stores the
input values
Step 4. Define a method calculate that calculates the bill amount based on the
distance travelled:
• If distance is less than or equal to 1 km, bill amount is Rs. 25.
• If distance is between 1-5 km, bill amount is Rs. 30 per km.
• If distance is between 5-10 km, bill amount is Rs. 35 per km.
• If distance is between 10-20 km, bill amount is Rs. 40 per km.
• If distance is more than 20 km, bill amount is Rs. 45 per km.
Step 5. Define a method display that prints the taxi details: Taxi number, Passenger's
name, Distance travelled and Bill amount
Step 6. Define the main method that:
• Creates an instance of the Cabservice class.
• Calls the input method to get user input.
• Calls the calculate method to calculate the bill amount.
• Calls the display method to print the taxi details.
Program:
import [Link];
class Cabservice
String taxino,name;
int d,amt;
Cabservice()
taxino = " ";
name = " ";
d= 0; amt = 0 ;
void input()
Scanner in = new Scanner([Link]);
[Link]("Enter taxi number: ");
taxino = [Link]();
[Link]("Enter name of the passenger: ");
name = [Link]();
[Link]("Enter distance travelled: ");
d = [Link]();
void calculate()
if (d<=1)
amt=25;
if (d>1&& d<=5)
amt=d*30;
if (d>5&&d<=10)
amt=d*35;
if (d>10&&d<=20)
amt=d*40;
if (d>20)
amt=d*45;
void display()
[Link]("Taxi No" +"\t"+"Name"+"\t\t"+ "Distance(km)"+
"\t"+ "Bill Amount(Rs.)");
[Link](taxino + "\t"+ name +"\t\t"+ d +"\t\t"+amt);
public static void main(String args[])
Cabservice ob= new Cabservice();
[Link]();
[Link]();
[Link]();
Output:
Enter taxi number: TN 01 A 1234
Enter name of the passenger: Anant
Enter distance travelled: 22
Taxi No Name Distance(km) Bill Amount(Rs.)
TN 01 A 1234 Anant 22 990
Result:
The program to demonstrate implementation of Constructor was compiled and
executed successfully
Ex. 2.a2 – Implementation of Parameterised Constructors
Aim:
To calculate the gross and net salary of an employee by the implementation of
parameterized constructor.
Algorithm:
Step 1. Define a class Employee_Sal with attributes: name, empno, basic, da, hra,
pf, gs, net .
Step 2. Create a constructor Employee_Sal that initializes the n(name), en(empno)
and bs(basic salary).
Step 3. Define a method compute that calculates the salary components:
• da = 30% of basic
• hra = 15% of basic
• pf = 12% of basic
• gs = basic + da + hra
• net = gs - pf
Step 4. Define a method display that prints: name, employee number, gross salary,
net salary
Step 5. Define the main method that:
• Creates a Scanner object to read input from the user and Prompts the user
to enter the employee's name, number, and basic salary.
• Creates an Employee_Sal object with the user's input.
• Call the compute method to calculate the salary components.
• Call the display method to print the employee's details
Program:
import [Link].*;
public class Employee_Sal
String name, empno;
int basic;
double da,hra,pf,gs,net;
Employee_Sal (String n, String en, int bs)
name=n;
empno=en;
basic=bs;
void compute()
da= basic*30.0/100.0;
hra=basic*15.0/100.0;
pf=basic*12.0/100.0;
gs=basic+da+hra; net=gs-pf;
void display()
[Link]("Name:"+ name);
[Link]("Employee Number :"+ empno);
[Link]("Gross salary : Rs. "+gs);
[Link]("Net Salary : Rs. "+net);
public static void main(String args[])
Scanner in = new Scanner([Link]);
String nm,enm;
int bsal;
[Link]("Enter Employee's Name, Employee No, Basic salary
:");
nm=[Link]();
enm=[Link]();
bsal=[Link]();
Employee_Sal ob=new Employee_Sal(nm,enm,bsal);
[Link]();
[Link]();
Output:
Enter Employee's Name, Employee No, Basic salary :Ananth
12345
20000
Name:Ananth
Employee Number :12345
Gross salary : Rs. 29000.0
Net Salary : Rs. 26600.0
Result:
The program to demonstrate implementation of Constructor was compiled and
executed successfully
2.b Inheritance and types
Ex. 2.b1 – Implementation of Single Inheritance
Aim:
To write a Java program to demonstrate the concept of single inheritance, where a
derived class inherits properties and methods from a single base class.
Algorithm:
Step 1: Define the base class Person:
• Declare attributes: name, age.
• Create a method displayPersonInfo() to display the name and age.
Step 2: Define the derived class Student which extends Person:
• Declare an additional attribute: college.
• Create a method displayStudentInfo() that calls displayPersonInfo() and
displays college.
Step 3: In the main method (main):
• Create an object of class Student.
• Assign values to name, age, and college using the object.
• Call displayStudentInfo() to display all the details.
Program:
class Person {
String name;
int age;
void displayPersonInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
// Derived class
class Student extends Person {
String college;
void displayStudentInfo() {
displayPersonInfo(); // calling superclass method
[Link]("College: " + college);
// Main class to run the program
public class SingleInheritanceDemo {
public static void main(String[] args) {
Student s = new Student();
[Link] = "Anitha";
[Link] = 20;
[Link] = "SIST";
[Link]();
Output:
Name: Anitha
Age: 20
College: SIST
Result:
The program to implement and demonstrate single inheritance in classes is
executed successfully
Ex. 2.b2 – Multi-level Inheritance
Aim:
To write a Java program to demonstrate the concept of multilevel inheritance by
creating a class Vehicle as the base class, Car as an intermediate class, and ElectricCar
as the derived class with multiple attributes and methods.
Algorithm:
Step 1: Define the base class Vehicle:
• Declare attributes: brand, type.
• Define method displayVehicleInfo() to print the brand and type.
Step 2: Define the derived class Car (extends Vehicle):
• Declare attributes: speed, numberOfDoors, fuelType.
• Define method displayCarInfo() to print these attributes.
Step 3: Define the derived class ElectricCar (extends Car):
• Declare attributes: batteryCapacity, range, fastCharging.
• Define method displayElectricCarInfo() to call all inherited display methods
and print its own attributes.
Step 4: In the main() method:
• Create an object of class ElectricCar.
• Assign values to all attributes using the object.
• Call displayElectricCarInfo() to print all the details.
Program:
// Base class
class Vehicle {
String brand;
String type;
void displayVehicleInfo() {
[Link]("Brand: " + brand);
[Link]("Type: " + type);
}
// Derived class from Vehicle
class Car extends Vehicle {
int speed;
int numberOfDoors;
String fuelType;
void displayCarInfo() {
[Link]("Top Speed: " + speed + " km/h");
[Link]("Doors: " + numberOfDoors);
[Link]("Fuel Type: " + fuelType);
// Derived class from Car (multilevel inheritance)
class ElectricCar extends Car {
int batteryCapacity;
int range;
boolean fastCharging;
void displayElectricCarInfo() {
displayVehicleInfo();
displayCarInfo();
[Link]("Battery Capacity: " + batteryCapacity + " kWh");
[Link]("Range: " + range + " km");
[Link]("Fast Charging: " + (fastCharging ? "Yes" : "No"));
}
public class MultilevelInheritanceDemo {
public static void main(String[] args) {
ElectricCar ec = new ElectricCar();
[Link] = "Tesla";
[Link] = "Sedan";
[Link] = 250;
[Link] = 4;
[Link] = "Electric";
[Link] = 100;
[Link] = 500;
[Link] = true;
[Link]();
Output:
Brand: Tesla
Type: Sedan
Top Speed: 250 km/h
Doors: 4
Fuel Type: Electric
Battery Capacity: 100 kWh
Range: 500 km
Fast Charging: Yes
Result:
Thus the program to implement multi-level inheritance is compiled and
executed successfully.
Ex. 2.b3 – Hierarchical inheritance
Aim:
To write a Java program to demonstrate the concept of hierarchical inheritance
where multiple derived classes inherit from a single base class.
Algorithm:
Step 1: Define a base class Device:
• Attributes: brand, model.
• Method: displayDeviceInfo() to print brand and model.
Step 2: Define derived class Smartphone that extends Device:
• Attribute: cameraMegapixel.
• Method: displaySmartphoneInfo() to display all smartphone info.
Step 3: Define another derived class Laptop that also extends Device:
• Attribute: ramSize.
• Method: displayLaptopInfo() to display all laptop info.
Step4: In the main() method:
• Create object of Smartphone, assign values, and call its method.
• Create object of Laptop, assign values, and call its method.
Program:
// Base class
class Device {
String brand;
String model;
void displayDeviceInfo() {
[Link]("Brand: " + brand);
[Link]("Model: " + model);
}
}
// Derived class 1
class Smartphone extends Device {
int cameraMegapixel;
void displaySmartphoneInfo() {
displayDeviceInfo();
[Link]("Camera: " + cameraMegapixel + " MP");
// Derived class 2
class Laptop extends Device {
int ramSize;
void displayLaptopInfo() {
displayDeviceInfo();
[Link]("RAM: " + ramSize + " GB");
// Main class
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
// Smartphone object
Smartphone phone = new Smartphone();
[Link] = "Samsung";
[Link] = "Galaxy S24";
[Link] = 108;
[Link]();
[Link]();
// Laptop object
Laptop laptop = new Laptop();
[Link] = "HP";
[Link] = "Pavilion 15";
[Link] = 16;
[Link]();
Output:
Brand: Samsung
Model: Galaxy S24
Camera: 108 MP
Brand: HP
Model: Pavilion 15
RAM: 16 GB
Result:
Thus the program to implement hierarchical inheritance is compiled and
executed successfully.
2.c Implementation of Polymorphism
Ex. 2.c1 – Implementation of Static Polymorphism
Aim:
To write a java program to implement method overloading in calculating
shapes, named “ShapeCalculator”.
Algorithm:
Step 1: Create a class “ShapeCalculator”
Step 2: Create method area with different arguments and return type
• int area(int side): for square
• int area(int length, int width): for rectangle
• double area(double radius): for circle
• double area(double base, double height): for triangle
Step 3: Initialize a ShapeCalculator object to access the overloaded area methods.
Step 4: Input the shape dimensions for square as squareSide, rectangle as
rectangleLength and rectangleWidth, circle as circleRadius, triangle as triangleBase
and triangleHeight.
Step 5: Calculate the area for square, rectangle, circle, triangle and call its function to
store the result.
Step 6: Print the results and Display the calculated areas for each shape.
Program:
class ShapeCalculator
// Overloaded method for calculating the area of a square
public int area(int side)
return side * side;
// Overloaded method for calculating the area of a rectangle
public int area(int length, int width)
return length * width;
// Overloaded method for calculating the area of a circle
public double area(double radius)
return [Link] * radius * radius;
// Overloaded method for calculating the area of a triangle
public double area(double base, double height)
return 0.5 * base * height;
public class Main
public static void main(String[] args)
ShapeCalculator calculator = new ShapeCalculator();
// Calculate and print the area of a square
int squareSide = 4;
[Link]("Area of square with side " + squareSide + ": " +
[Link](squareSide));
// Calculate and print the area of a rectangle
int rectangleLength = 5;
int rectangleWidth = 3;
[Link]("Area of rectangle with length " + rectangleLength +
" and width " + rectangleWidth + ": " + [Link](rectangleLength,
rectangleWidth));
// Calculate and print the area of a circle
double circleRadius = 2.5;
[Link]("Area of circle with radius " + circleRadius + ": " +
[Link](circleRadius));
// Calculate and print the area of a triangle
double triangleBase = 6.0;
double triangleHeight = 4.0;
[Link]("Area of triangle with base " + triangleBase + " and
height " +triangleHeight + ": " + [Link](triangleBase, triangleHeight));
Output:
Area of square with side 4: 16
Area of rectangle with length 5 and width 3: 15
Area of circle with radius 2.5: 19.634954084936208
Area of triangle with base 6.0 and height 4.0: 12.0
Result:
Thus the program to implement static polymorphism by demonstrating area of
various shapes has been successfully executed.
Ex. 2.c2 – Implementation of runtime polymorphism
Aim:
To write a java program to implement method overriding in calculating the area of
rectangle and triangle.
Algorithm:
Step 1: Create the class Figure with attributes dim1, dim2 and constructor
Step 2: Create the classes for different shapes with Figure as base class
Step 3: implement code for method “double area”
Step 4: Create shape objects for figure reference, rectangle and triangle with their
required dimensions(x,y):
Step 5: Declare a Figure reference variable figref.
Step 6: Assign the Rectangle object to figref and Calculate and print the area of the
Rectangle using [Link]().
Step 7:Assign the Triangle object to figref And Calculate and print the area of the
Triangle using [Link]().
Step 8: Assign the Figure object to figref and Calculate and print the area of the Figure
using [Link](). 6: Print the results and Display the calculated areas for each shape.
Program:
class Figure
double dim1;
double dim2;
Figure(double a,double b)
dim1=a;
dim2=b;
double area()
[Link]("Area for Figure is undefined");
return 0;
}
class Rectangle extends Figure
Rectangle (double a,double b)
super(a,b);
double area()
[Link]("Inside Area for Rectangle");
return dim1 * dim2;
class Triangle extends Figure
Triangle (double a,double b)
super(a,b);
double area()
[Link]("Inside Area for Triangle");
return dim1 * dim2/2;
}
class Findareas {
public static void main(String[] args) {
Figure f=new Figure(10,10);
Rectangle r= new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Figure figref;
figref=r;
[Link]("Area is "+[Link]());
figref=t;
[Link]("Area is "+[Link]());
figref=f;
[Link]("Area is "+[Link]());
Output:
Inside Area for Rectangle
Area is 45.0
Inside Area for Triangle
Area is 40.0
Area for Figure is undefined
Area is 0.0
Result:
2.d Abstraction
Ex. 2.d – Program to implement abstraction
Write a Java program that demonstrates abstraction through a calculator with user
input. The program includes an abstract class Calculator, concrete classes for addition,
subtraction, multiplication, and division, and a main class to perform these operations
based on user input.
Aim:
To demonstrate abstraction through a calculator that performs basic arithmetic
operations (+, -, *, /) based on user input.
Algorithm:
Step 1. Import the [Link] class to read user input.
[Link] an abstract class Calculator with two double fields (number1 and number2)
and a constructor.
[Link] an abstract method calculate() for the calculation.
[Link] four classes (Addition, Subtraction, Multiplication, and Division) that extend
the Calculator class.
[Link] the calculate() method in each class to perform the respective calculation.
[Link] a main method in the Main class.
[Link] user input using the Scanner class: num1, num2, operation. [Link] a variable
(calculator).
[Link] the calculation based on the user input using a switch statement: Instantiate
the appropriate calculation class.
Call the calculate() method and print the result. [Link] the Scanner.
Program:
import [Link];
// Abstract class Calculator
abstract class Calculator {
double number1, number2;
// Constructor
public Calculator(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
// Abstract method for calculation
abstract double calculate();
// Addition class
class Addition extends Calculator {
public Addition(double number1, double number2) {
super(number1, number2);
@Override
double calculate() {
return number1 + number2;
// Subtraction class
class Subtraction extends Calculator {
public Subtraction(double number1, double number2) {
super(number1, number2);
@Override
double calculate() {
return number1 - number2;
// Multiplication class
class Multiplication extends Calculator {
public Multiplication(double number1, double number2) {
super(number1, number2);
@Override
double calculate() {
return number1 * number2;
class Division extends Calculator {// Division class
public Division(double number1, double number2) {
super(number1, number2);
@Override
double calculate() {
if (number2 != 0) {
return number1 / number2;
else {
[Link]("Error: Division by zero");
return [Link];
public class Main1 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Getting user input
[Link]("Enter first number: ");
double num1 = [Link]();
[Link]("Enter second number: ");
double num2 = [Link]();
[Link]("Enter operation (+, -, *, /): ");
char operation = [Link]().charAt(0);
Calculator calculator;
// Performing calculation based on user input
switch (operation) {
case '+':
calculator = new Addition(num1, num2);
[Link]("Result: " + [Link]());
break;
case '-':
calculator = new Subtraction(num1, num2);
[Link]("Result: " + [Link]());
break;
case '*':
calculator = new Multiplication(num1, num2);
[Link]("Result: " + [Link]());
break;
case '/':
calculator = new Division(num1, num2);
[Link]("Result: " + [Link]());
break;
default:
[Link]("Invalid operation");
break;
[Link]();
Output:
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
Result: 15.0
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): -
Result: 5.0
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): *
Result: 50.0
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): / Result: 2.0
Result:
Thus the program to demonstrate abstraction is compiled and executed
successfully.