0% found this document useful (0 votes)
4 views25 pages

Unit 2 Java Programs

The document outlines various Java programming exercises focused on Object-Oriented Programming concepts, including the implementation of constructors, inheritance (single, multi-level, and hierarchical), and polymorphism (static and runtime). Each exercise provides a clear aim, algorithm, and sample code demonstrating the concepts, such as calculating taxi fares, employee salaries, and areas of different shapes. The document concludes with successful execution results for each program, showcasing the practical application of these programming principles.

Uploaded by

xokemo2424
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)
4 views25 pages

Unit 2 Java Programs

The document outlines various Java programming exercises focused on Object-Oriented Programming concepts, including the implementation of constructors, inheritance (single, multi-level, and hierarchical), and polymorphism (static and runtime). Each exercise provides a clear aim, algorithm, and sample code demonstrating the concepts, such as calculating taxi fares, employee salaries, and areas of different shapes. The document concludes with successful execution results for each program, showcasing the practical application of these programming principles.

Uploaded by

xokemo2424
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/ 25

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 java.util.Scanner;

class Cabservice

String taxino,name;

int d,amt;
Cabservice()

taxino = " ";

name = " ";

d= 0; amt = 0 ;

void input()

Scanner in = new Scanner(System.in);

System.out.print("Enter taxi number: ");

taxino = in.nextLine();

System.out.print("Enter name of the passenger: ");

name = in.nextLine();

System.out.print("Enter distance travelled: ");

d = in.nextInt();

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()

System.out.println("Taxi No" +"\t"+"Name"+"\t\t"+ "Distance(km)"+


"\t"+ "Bill Amount(Rs.)");

System.out.println(taxino + "\t"+ name +"\t\t"+ d +"\t\t"+amt);

public static void main(String args[])

Cabservice ob= new Cabservice();

ob.input();

ob.calculate();

ob.display();

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 java.util.*;

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()

System.out.println("Name:"+ name);

System.out.println("Employee Number :"+ empno);

System.out.println("Gross salary : Rs. "+gs);

System.out.println("Net Salary : Rs. "+net);

public static void main(String args[])

Scanner in = new Scanner(System.in);

String nm,enm;

int bsal;
System.out.print("Enter Employee's Name, Employee No, Basic salary
:");

nm=in.nextLine();

enm=in.next();

bsal=in.nextInt();

Employee_Sal ob=new Employee_Sal(nm,enm,bsal);

ob.compute();

ob.display();

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() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

}
// Derived class

class Student extends Person {

String college;

void displayStudentInfo() {

displayPersonInfo(); // calling superclass method

System.out.println("College: " + college);

// Main class to run the program

public class SingleInheritanceDemo {

public static void main(String[] args) {

Student s = new Student();

s.name = "Anitha";

s.age = 20;

s.college = "SIST";

s.displayStudentInfo();

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() {

System.out.println("Brand: " + brand);

System.out.println("Type: " + type);


}

// Derived class from Vehicle

class Car extends Vehicle {

int speed;

int numberOfDoors;

String fuelType;

void displayCarInfo() {

System.out.println("Top Speed: " + speed + " km/h");

System.out.println("Doors: " + numberOfDoors);

System.out.println("Fuel Type: " + fuelType);

// Derived class from Car (multilevel inheritance)

class ElectricCar extends Car {

int batteryCapacity;

int range;

boolean fastCharging;

void displayElectricCarInfo() {

displayVehicleInfo();

displayCarInfo();

System.out.println("Battery Capacity: " + batteryCapacity + " kWh");

System.out.println("Range: " + range + " km");

System.out.println("Fast Charging: " + (fastCharging ? "Yes" : "No"));

}
public class MultilevelInheritanceDemo {

public static void main(String[] args) {

ElectricCar ec = new ElectricCar();

ec.brand = "Tesla";

ec.type = "Sedan";

ec.speed = 250;

ec.numberOfDoors = 4;

ec.fuelType = "Electric";

ec.batteryCapacity = 100;

ec.range = 500;

ec.fastCharging = true;

ec.displayElectricCarInfo();

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() {

System.out.println("Brand: " + brand);

System.out.println("Model: " + model);

}
}

// Derived class 1

class Smartphone extends Device {

int cameraMegapixel;

void displaySmartphoneInfo() {

displayDeviceInfo();

System.out.println("Camera: " + cameraMegapixel + " MP");

// Derived class 2

class Laptop extends Device {

int ramSize;

void displayLaptopInfo() {

displayDeviceInfo();

System.out.println("RAM: " + ramSize + " GB");

// Main class

public class HierarchicalInheritanceDemo {

public static void main(String[] args) {

// Smartphone object
Smartphone phone = new Smartphone();

phone.brand = "Samsung";

phone.model = "Galaxy S24";

phone.cameraMegapixel = 108;

phone.displaySmartphoneInfo();

System.out.println();

// Laptop object

Laptop laptop = new Laptop();

laptop.brand = "HP";

laptop.model = "Pavilion 15";

laptop.ramSize = 16;

laptop.displayLaptopInfo();

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 Math.PI * 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;

System.out.println("Area of square with side " + squareSide + ": " +


calculator.area(squareSide));

// Calculate and print the area of a rectangle


int rectangleLength = 5;

int rectangleWidth = 3;

System.out.println("Area of rectangle with length " + rectangleLength +


" and width " + rectangleWidth + ": " + calculator.area(rectangleLength,
rectangleWidth));

// Calculate and print the area of a circle

double circleRadius = 2.5;

System.out.println("Area of circle with radius " + circleRadius + ": " +


calculator.area(circleRadius));

// Calculate and print the area of a triangle

double triangleBase = 6.0;

double triangleHeight = 4.0;

System.out.println("Area of triangle with base " + triangleBase + " and


height " +triangleHeight + ": " + calculator.area(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 figref.area().

Step 7:Assign the Triangle object to figref And Calculate and print the area of the
Triangle using figref.area().

Step 8: Assign the Figure object to figref and Calculate and print the area of the Figure
using figref.area(). 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()

System.out.println("Area for Figure is undefined");

return 0;
}

class Rectangle extends Figure

Rectangle (double a,double b)

super(a,b);

double area()

System.out.println("Inside Area for Rectangle");

return dim1 * dim2;

class Triangle extends Figure

Triangle (double a,double b)

super(a,b);

double area()

System.out.println("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;

System.out.println("Area is "+figref.area());

figref=t;

System.out.println("Area is "+figref.area());

figref=f;

System.out.println("Area is "+figref.area());

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 java.util.Scanner class to read user input.

2.Create an abstract class Calculator with two double fields (number1 and number2)
and a constructor.

3.Define an abstract method calculate() for the calculation.

4.Create four classes (Addition, Subtraction, Multiplication, and Division) that extend
the Calculator class.

5.Override the calculate() method in each class to perform the respective calculation.
6.Create a main method in the Main class.

7.Read user input using the Scanner class: num1, num2, operation. 8.Create a variable
(calculator).

9.Perform the calculation based on the user input using a switch statement: Instantiate
the appropriate calculation class.

Call the calculate() method and print the result. 10.Close the Scanner.

Program:

import java.util.Scanner;

// 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 {

System.out.println("Error: Division by zero");

return Double.NaN;

public class Main1 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


// Getting user input

System.out.print("Enter first number: ");

double num1 = scanner.nextDouble();

System.out.print("Enter second number: ");

double num2 = scanner.nextDouble();

System.out.print("Enter operation (+, -, *, /): ");

char operation = scanner.next().charAt(0);

Calculator calculator;

// Performing calculation based on user input

switch (operation) {

case '+':

calculator = new Addition(num1, num2);

System.out.println("Result: " + calculator.calculate());

break;

case '-':

calculator = new Subtraction(num1, num2);

System.out.println("Result: " + calculator.calculate());

break;

case '*':

calculator = new Multiplication(num1, num2);

System.out.println("Result: " + calculator.calculate());

break;

case '/':

calculator = new Division(num1, num2);

System.out.println("Result: " + calculator.calculate());

break;
default:

System.out.println("Invalid operation");

break;

scanner.close();

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.

You might also like