[go: up one dir, main page]

0% found this document useful (0 votes)
122 views16 pages

Lab Report 1

The document is a lab report submitted by a student named Md. Tasnimur Rahman Shakir to their teacher Mahbubur Rahman. It discusses implementing inheritance in Java by creating hierarchies for shapes, employees, and vehicles with base classes and derived classes. Code examples are provided to calculate areas, perimeters, salaries, and fuel consumption for the classes in each hierarchy.
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)
122 views16 pages

Lab Report 1

The document is a lab report submitted by a student named Md. Tasnimur Rahman Shakir to their teacher Mahbubur Rahman. It discusses implementing inheritance in Java by creating hierarchies for shapes, employees, and vehicles with base classes and derived classes. Code examples are provided to calculate areas, perimeters, salaries, and fuel consumption for the classes in each hierarchy.
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/ 16

Green University of Bangladesh

Department of Computer Science and Engineering (CSE)


Semester: (Spring, Year: 2023), B.Sc. in CSE (Day)

Lab Report-1 On Inheritance

Students Details
Name ID
Md. Tasnimur Rahman Shakir 221902285

Submission Date: 07-06-2023


Course Teacher’s Name: Mahbubur Rahman

[For teachers use only: Don’t write anything inside this box]

Lab Project Status

Marks: Signature:

Comments: Date:
Contents

1 Introduction 2
1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.1 Code & Output . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Design Goals/Objectives . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.5 Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1
Chapter 1

Introduction

1.1 Overview
Inheritance is a fundamental concept in object-oriented programming (OOP) that al-
lows classes to inherit properties and behavior from other classes. In Java, inheritance
forms the basis of code reuse and abstraction, enabling developers to create hierarchical
relationships between classes and build upon existing code to create new classes with
additional features.

1.2 Motivation
The motivation behind using inheritance in Java is to achieve several key benefits:

1. Code Reusablity.

2. Abstraction and Modularity.

3. Polymorphism.

4. Extensibility.

1.3 Implementation

1.3.1 Code & Output


Problem 1

Shape Hierarchy: Create a shape hierarchy with a base class "Shape" and derived
classes such as "Circle," "Rectangle," and "Triangle." Implement methods for calculat-
ing the area and perimeter of each shape.

package LabReportOne;

2
import java.util.Scanner;

class Shape {
double width, height;
public Shape(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea(){
System.out.println("");
return 0;
}
public double getPerimeter(){
System.out.println("");
return 0;
}
}
class Circle extends Shape {

public Circle(double radius) {


super(radius, radius);
}

@Override
public double getArea() {
return Math.PI * width * width;
}

@Override
public double getPerimeter() {
return 2 * Math.PI * width;
}
}
class Rectangle extends Shape {

public Rectangle(double width, double height) {


super(width, height);
}

@Override
public double getArea() {
return width * height;
}

@Override
public double getPerimeter() {
return 2 * (width + height);

3
}
}
class Triangle extends Shape {

public Triangle(double base, double height) {


super(base, height);
}

@Override
public double getArea() {
return (width * height) / 2;
}

@Override
public double getPerimeter() {
return width + height + Math.sqrt(width * width + height * height);
}
}

public class ShapeHierarchy {


public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
// Get dimensions for Triangle
System.out.print("Enter base of the triangle: ");
double base = scanner.nextDouble();
System.out.print("Enter height of the triangle: ");
double height = scanner.nextDouble();
Shape triangle = new Triangle(base, height);
System.out.println("Area Of Triangle(" + base + ", " + height + "): " +
System.out.println("Perimeter Of Triangle(" + base + ", " + height + ")

System.out.println();

// Get dimensions for Rectangle


System.out.print("Enter width of the rectangle: ");
double width = scanner.nextDouble();
System.out.print("Enter height of the rectangle: ");
height = scanner.nextDouble();
Shape rectangle = new Rectangle(width, height);
System.out.println("Area Of Rectangle(" + width + ", " + height + "): "
System.out.println("Perimeter Of Rectangle(" + width + ", " + height +

System.out.println();

// Get dimension for Circle


System.out.print("Enter radius of the circle: ");
double radius = scanner.nextDouble();
Shape circle = new Circle(radius);

4
System.out.println("Area Of Circle(" + radius + "): " + circle.getArea(
System.out.println("Perimeter Of Circle(" + radius + "): " + circle.get
}
}
}

Output 1

Problem 2

Employee Hierarchy: Create an employee hierarchy with a base class "Employee"


and derived classes such as "Manager," "Developer," and "Salesperson." Implement
methods to calculate the salary of each employee based on their role and experience
level.

import java.util.Scanner;

class Employee {
final String name;
String role;
double experience;
double basicSalary;

public Employee(String name, String role, int experience, double basicSalary) {


this.name = name;
this.role = role;
this.basicSalary = basicSalary;

5
if (experience >= 10) {
this.experience = 0.5;
} else if (experience >= 5) {
this.experience = 0.4;
} else {
this.experience = 0.25;
}
}

public double calculateSalary() {


double salary = basicSalary + (basicSalary * experience);
return salary;
}
}

class Manager extends Employee {


public Manager(String name, int experience, double basicSalary) {
super(name, "Manager", experience, basicSalary);
}
}

class Developer extends Employee {


public Developer(String name, int experience, double basicSalary) {
super(name, "Developer", experience, basicSalary);
}
}

class Salesperson extends Employee {


public Salesperson(String name, int experience, double basicSalary) {
super(name, "Salesperson", experience, basicSalary);
}
}

public class EmployeeHierachy {

public static void main(String[] args) {


Manager manager;
Developer developer;
Salesperson salesperson;
// Get Manager details
try (Scanner scanner = new Scanner(System.in)) {
// Get Manager details
System.out.print("Enter Manager’s name: ");
String managerName = scanner.nextLine();
System.out.print("Enter Manager’s experience (in years): ");
int managerExperience = scanner.nextInt();
System.out.print("Enter Manager’s basic salary: ");
double managerBasicSalary = scanner.nextDouble();

6
scanner.nextLine(); // Consume newline character
manager = new Manager(managerName, managerExperience, managerBasicSalar
// Get Developer details
System.out.print("Enter Developer’s name: ");
String developerName = scanner.nextLine();
System.out.print("Enter Developer’s experience (in years): ");
int developerExperience = scanner.nextInt();
System.out.print("Enter Developer’s basic salary: ");
double developerBasicSalary = scanner.nextDouble();
scanner.nextLine(); // Consume newline character
developer = new Developer(developerName, developerExperience, developer
// Get Salesperson details
System.out.print("Enter Salesperson’s name: ");
String salespersonName = scanner.nextLine();
System.out.print("Enter Salesperson’s experience (in years): ");
int salespersonExperience = scanner.nextInt();
System.out.print("Enter Salesperson’s basic salary: ");
double salespersonBasicSalary = scanner.nextDouble();
scanner.nextLine(); // Consume newline character
salesperson = new Salesperson(salespersonName, salespersonExperience, s
}

// Print their salaries


System.out.println("Manager salary(" + manager.name + "): " + manager.calcu
System.out.println("Developer salary(" + developer.name + "): " + developer
System.out.println("Salesperson salary(" + salesperson.name + "): " + sales
}
}

Output 2

7
Problem 3

Vehicle Inheritance: Create a vehicle hierarchy with a base class "Vehicle" and derived
classes such as "Car," "Motorcycle," and "Truck." Implement methods to calculate the
fuel consumption and display the details of each vehicle.

import java.util.Scanner;

class Vehicle {
String make;
String model;
int year;
double fuelEfficiency;

public Vehicle(String make, String model, int year, double fuelEfficiency) {


this.make = make;
this.model = model;
this.year = year;
this.fuelEfficiency = fuelEfficiency;
}

public double calculateFuelConsumption(double distance) {


return distance / fuelEfficiency;
}

public void displayDetails() {


System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Fuel efficiency: " + fuelEfficiency);
}
}

class Car extends Vehicle {


private final int numberOfSeats;

public Car(String make, String model, int year, double fuelEfficiency, int numb
super(make, model, year, fuelEfficiency);
this.numberOfSeats = numberOfSeats;
}

public int getNumberOfSeats() {


return numberOfSeats;
}
}

class Motorcycle extends Vehicle {


private final boolean hasSidecar;

8
public Motorcycle(String make, String model, int year, double fuelEfficiency, b
super(make, model, year, fuelEfficiency);
this.hasSidecar = hasSidecar;
}

public boolean hasSidecar() {


return hasSidecar;
}
}

class Truck extends Vehicle {


private final String cargoCapacity;

public Truck(String make, String model, int year, double fuelEfficiency, String
super(make, model, year, fuelEfficiency);
this.cargoCapacity = cargoCapacity;
}

public String getCargoCapacity() {


return cargoCapacity;
}
}

public class VehicleInheritance {


public static void main(String[] args) {
Car car;
Motorcycle motorcycle;
Truck truck;

// Get travel distance from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the travel distance (in miles): ");
double distance = scanner.nextDouble();

// Get Car details


scanner.nextLine(); // Consume newline character
System.out.print("Enter Car’s make: ");
String carMake = scanner.nextLine();
System.out.print("Enter Car’s model: ");
String carModel = scanner.nextLine();
System.out.print("Enter Car’s year: ");
int carYear = scanner.nextInt();
System.out.print("Enter Car’s fuel efficiency (miles per litre): ");
double carFuelEfficiency = scanner.nextDouble();
System.out.print("Enter Car’s number of seats: ");
int carNumberOfSeats = scanner.nextInt();
scanner.nextLine(); // Consume newline character

9
car = new Car(carMake, carModel, carYear, carFuelEfficiency, carNumberOfSea

// Get Motorcycle details


System.out.print("Enter Motorcycle’s make: ");
String motorcycleMake = scanner.nextLine();
System.out.print("Enter Motorcycle’s model: ");
String motorcycleModel = scanner.nextLine();
System.out.print("Enter Motorcycle’s year: ");
int motorcycleYear = scanner.nextInt();
System.out.print("Enter Motorcycle’s fuel efficiency (miles per litre): ");
double motorcycleFuelEfficiency = scanner.nextDouble();
System.out.print("Does the Motorcycle have a sidecar? (true/false): ");
boolean motorcycleHasSidecar = scanner.nextBoolean();
scanner.nextLine(); // Consume newline character
motorcycle = new Motorcycle(motorcycleMake, motorcycleModel, motorcycleYear

// Get Truck details


System.out.print("Enter Truck’s make: ");
String truckMake = scanner.nextLine();
System.out.print("Enter Truck’s model: ");
String truckModel = scanner.nextLine();
System.out.print("Enter Truck’s year: ");
int truckYear = scanner.nextInt();
System.out.print("Enter Truck’s fuel efficiency (miles per litre): ");
double truckFuelEfficiency = scanner.nextDouble();
scanner.nextLine(); // Consume newline character
System.out.print("Enter Truck’s cargo capacity: ");
String truckCargoCapacity = scanner.nextLine();
truck = new Truck(truckMake, truckModel, truckYear, truckFuelEfficiency, tr

scanner.close();

// Print fuel consumption and vehicle details


double carFuelConsumption = car.calculateFuelConsumption(distance);
System.out.println("The car’s fuel consumption is " + carFuelConsumption +
car.displayDetails();
System.out.println();

double motorcycleFuelConsumption = motorcycle.calculateFuelConsumption(dist


System.out.println("The Motorcycle’s fuel consumption is " + motorcycleFuel
motorcycle.displayDetails();
System.out.println();

double truckFuelConsumption = truck.calculateFuelConsumption(distance);


System.out.println("The Truck’s fuel consumption is " + truckFuelConsumptio
truck.displayDetails();
}
}

10
Output 1

Problem 4

School System: Create a school system with a base class "Person" and derived classes
such as "Student" and "Teacher." Implement methods to calculate the average grade of
a student and display the subjects taught by a teacher.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

class Person {
final String name;

11
final int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}

class Student extends Person {


private final List<Integer> grades;

public Student(String name, int age, List<Integer> grades) {


super(name, age);
this.grades = grades;
}

public double calculateAverageGrade() {


int totalGrades = grades.stream().mapToInt(Integer::intValue).sum();
int numGrades = grades.size();
return (double) totalGrades / numGrades;
}

class Teacher extends Person {


private final List<String> subjects;

public Teacher(String name, int age, List<String> subjects) {


super(name, age);
this.subjects = subjects;
}

public void displaySubjects() {


for (String subject : subjects) {
System.out.println(subject);
}
}
}

public class SchoolSystem {


public static void main(String[] args) {
Student student;
Teacher teacher;
// Get student details
try (Scanner scanner = new Scanner(System.in)) {
// Get student details
System.out.print("Enter student’s name: ");
String studentName = scanner.nextLine();

12
System.out.print("Enter student’s age: ");
int studentAge = scanner.nextInt();
scanner.nextLine(); // Consume newline character
System.out.print("Enter student’s grades (separated by spaces): ");
String[] gradeTokens = scanner.nextLine().split(" ");
List<Integer> studentGrades = new ArrayList<>();
for (String gradeToken : gradeTokens) {
studentGrades.add(Integer.valueOf(gradeToken));
} student = new Student(studentName, studentAge, studentGrades);
// Get teacher details
System.out.print("Enter teacher’s name: ");
String teacherName = scanner.nextLine();
System.out.print("Enter teacher’s age: ");
int teacherAge = scanner.nextInt();
scanner.nextLine(); // Consume newline character
System.out.print("Enter teacher’s subjects (separated by commas): ");
String subjectsInput = scanner.nextLine();
List<String> teacherSubjects = Arrays.asList(subjectsInput.split("\\s*,
teacher = new Teacher(teacherName, teacherAge, teacherSubjects);
}

// Print student’s average grade and details


double averageGrade = student.calculateAverageGrade();
System.out.println("The student’s average grade is " + averageGrade);
System.out.println("The student’s name is " + student.name + " and age is "
System.out.println();

// Print teacher’s details


System.out.println("The teacher’s name is " + teacher.name + " and age is "
System.out.println("subjects taught by a teacher: ");
teacher.displaySubjects();
}
}

13
Output 1

1.4 Design Goals/Objectives


The objective of inheritance in Java is to facilitate code reuse, improve maintainability,
and promote modality in software development. By using inheritance, developers can
create new classes that inherit the attributes and methods of existing classes, reducing
redundant code and promoting a more efficient and structured approach to program-
ming. Inheritance also allows for the creation of specialized classes that can override
or extend the behavior of their parent classes, enabling customization and flexibility in
software design.

1.5 Application
1. Creating class hierarchies: Inheritance allows the creation of parent and child
classes, enabling the reuse of code and promoting a hierarchical structure for
related classes.

2. Code reusability: Inheritance enables the child classes to inherit attributes and
methods from parent classes, reducing code duplication and promoting efficient
development.

3. Polymorphism: Inheritance facilitates polymorphism, allowing objects of differ-


ent classes to be treated as objects of a common superclass, enhancing flexibility
and extensibility.

Overall, inheritance in Java is applied for creating class hierarchies, promoting code
reusability, facilitating polymorphism, and in the development of frameworks and li-
braries. [1]

14
References

[1] Omid C Farokhzad and Robert Langer. Impact of nanotechnology on drug delivery.
ACS nano, 3(1):16–20, 2009.

15

You might also like