0% found this document useful (0 votes)
26 views22 pages

Oop Assignment

The document outlines key concepts of object-oriented programming (OOP) including abstraction, encapsulation, inheritance, and polymorphism, illustrated with Java code examples. It demonstrates class hierarchies for vehicles, bank accounts, shapes, animals, and employee management systems, showcasing how these concepts are implemented in Java. Additionally, it includes examples of encapsulation and polymorphism through interfaces and class inheritance.

Uploaded by

solianaadhanom2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views22 pages

Oop Assignment

The document outlines key concepts of object-oriented programming (OOP) including abstraction, encapsulation, inheritance, and polymorphism, illustrated with Java code examples. It demonstrates class hierarchies for vehicles, bank accounts, shapes, animals, and employee management systems, showcasing how these concepts are implemented in Java. Additionally, it includes examples of encapsulation and polymorphism through interfaces and class inheritance.

Uploaded by

solianaadhanom2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

MICROLINK INFORMATION AND BUSINESS COLLAGE

OOP INDIVIDUAL ASSIGNMENT

Name soliana adhanom

Id no mdr/1634/19

department SE
Key concept

-Abstraction Show only what’s necessary, hide the rest.

-Encapsulation Bundle data and methods together, control access.

-|nheritance Create new classes from existing ones to reuse and extend functionality.

-Polymorphism| One thing can behave in multiple ways.

1 Java implementation of the class hierarchy for the Vehicle system, along with the creation of objects for `Car` and `Motorcycle` to demonstrate inheritance

// Base class: Vehicle

class Vehicle {

private String make;

private String model;

private int year;

// Constructor

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

this.make = make;

this.model = model;

this.year = year;

// Methods

public void start() {

System.out.println(make + " " + model + " is starting.");

public void stop() {

System.out.println(make + " " + model + " is stopping.");

public void displayDetails() {

System.out.println("Vehicle Details: " + year + " " + make + " " + model);

// Derived class: Car (inherits from Vehicle)

class Car extends Vehicle {

private int numDoors;

// Constructor

public Car(String make, String model, int year, int numDoors) {

super(make, model, year); // Call the base class constructor


this.numDoors = numDoors;

// Override displayDetails() to include the number of doors

@Override

public void displayDetails() {

super.displayDetails(); // Call the base class method

System.out.println("Number of Doors: " + numDoors);

// Derived class: Motorcycle (inherits from Vehicle)

class Motorcycle extends Vehicle {

private boolean hasSideCar;

// Constructor

public Motorcycle(String make, String model, int year, boolean hasSideCar) {

super(make, model, year); // Call the base class constructor

this.hasSideCar = hasSideCar;

// Override displayDetails() to include whether it has a sidecar

@Override

public void displayDetails() {

super.displayDetails(); // Call the base class method

System.out.println("Has Sidecar: " + (hasSideCar ? "Yes" : "No"));

// Main class to demonstrate inheritance

public class Main {

public static void main(String[] args) {

// Create a Car object

Car car = new Car("Toyota", "Camry", 2023, 4);

car.start();

car.displayDetails();

car.stop();

System.out.println(); // Add a separator for clarity


// Create a Motorcycle object

Motorcycle motorcycle = new Motorcycle("Harley-Davidson", "Sportster", 2022, true);

motorcycle.start();

motorcycle.displayDetails();

motorcycle.stop();

Output:

Toyota Camry is starting.

Vehicle Details: 2023 Toyota Camry

Number of Doors: 4

Toyota Camry is stopping.

Harley-Davidson Sportster is starting.

Vehicle Details: 2022 Harley-Davidson Sportster

Has Sidecar: Yes

Harley-Davidson Sportster is stopping.

**Vehicle Class**: The base class with attributes `make`, `model`, and `year`, and methods `start()`, `stop()`, and `displayDetails()`.

**Car Class**: Inherits from `Vehicle` and adds an attribute `numDoors`. It overrides `displayDetails()` to include the number of doors.

**Motorcycle Class**: Inherits from `Vehicle` and adds an attribute `hasSideCar`. It overrides `displayDetails()` to include whether it has a sidecar.

**Main Class**: Demonstrates inheritance by creating objects of `Car` and `Motorcycle` and calling their methods.

2 In Java, encapsulation is achieved by using **private** access modifiers for attributes and providing **public methods** (getters and setters) to interact with those
attributes. Below is the implementation of the `BankAccount` class in Java, demonstrating encapsulation:

```java

class BankAccount {

// Private attributes

private String accountNumber;

private String accountHolderName;

private double balance;

// Constructor

public BankAccount(String accountNumber, String accountHolderName, double balance) {

this.accountNumber = accountNumber;

this.accountHolderName = accountHolderName;

this.balance = balance;

// Public method to deposit money


public void deposit(double amount) {

if (amount > 0) {

this.balance += amount;

System.out.println("Deposited: $" + amount);

} else {

System.out.println("Deposit amount must be positive.");

// Public method to withdraw money

public void withdraw(double amount) {

if (amount > 0) {

if (this.balance >= amount) {

this.balance -= amount;

System.out.println("Withdrew: $" + amount);

} else {

System.out.println("Insufficient balance.");

} else {

System.out.println("Withdrawal amount must be positive.");

// Public method to get the current balance

public double getBalance() {

return this.balance;

// Public method to display account details

public void displayAccountDetails() {

System.out.println("Account Number: " + this.accountNumber);

System.out.println("Account Holder Name: " + this.accountHolderName);

System.out.println("Balance: $" + this.balance);

public class Main {

public static void main(String[] args) {


// Create an object of BankAccount

BankAccount account = new BankAccount("123456789", "John Doe", 1000);

// Accessing methods without directly modifying attributes

account.displayAccountDetails(); // Display initial details

account.deposit(500); // Deposit $500

account.withdraw(200); // Withdraw $200

// Display updated details

account.displayAccountDetails();

```

### Explanation:

1. **Private Attributes**: The attributes (`accountNumber`, `accountHolderName`, and `balance`) are declared as `private`, so they cannot be accessed directly from outside
the class.

2. **Public Methods**: Methods like `deposit`, `withdraw`, `getBalance`, and `displayAccountDetails` are `public`, allowing controlled access to the private attributes.

3. **Encapsulation**: The internal state of the object is protected, and all interactions are done through the public methods.

Output:

When you run the `Main` class, the output will be:

Account Number: 123456789

Account Holder Name: John Doe

Balance: $1000.0

Deposited: $500.0

Withdrew: $200.0

Account Number: 123456789

Account Holder Name: John Doe

Balance: $1300.0

This demonstrates encapsulation in Java, where the internal state of the `BankAccount` object is accessed and modified only through its public methods.

3Here is the Java implementation of the task:

```java

// Abstract class Shape

abstract class Shape {

// Abstract method to calculate area

public abstract double calculateArea();


// Non-abstract method to display a message

public void display() {

System.out.println("This is a shape.");

// Subclass Circle

class Circle extends Shape {

private double radius;

// Constructor for Circle

public Circle(double radius) {

this.radius = radius;

// Implementation of calculateArea() for Circle

@Override

public double calculateArea() {

return Math.PI * radius * radius;

// Subclass Rectangle

class Rectangle extends Shape {

private double length;

private double width;

// Constructor for Rectangle

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

// Implementation of calculateArea() for Rectangle

@Override

public double calculateArea() {

return length * width;


}

// Main class to demonstrate abstraction

public class Main {

public static void main(String[] args) {

// Create a Circle object

Shape circle = new Circle(5.0);

System.out.println("Area of Circle: " + circle.calculateArea());

circle.display();

// Create a Rectangle object

Shape rectangle = new Rectangle(4.0, 6.0);

System.out.println("Area of Rectangle: " + rectangle.calculateArea());

rectangle.display();

**Abstract Class `Shape`:**

- Contains an abstract method `calculateArea()` that must be implemented by subclasses.

- Contains a non-abstract method `display()` that prints "This is a shape."

**Subclass `Circle`:**

- Implements the `calculateArea()` method to calculate the area of a circle using the formula `π * radius * radius`.

**Subclass `Rectangle`:**

- Implements the `calculateArea()` method to calculate the area of a rectangle using the formula `length * width`.

**Main Class:**

- Creates objects of `Circle` and `Rectangle`.

- Calls the `calculateArea()` and `display()` methods to demonstrate abstraction.

Output:

Area of Circle: 78.53981633974483

This is a shape.

Area of Rectangle: 24.0

This is a shape.

This code demonstrates abstraction by using an abstract class and implementing its methods in subclasses. The `calculateArea()` method is specific to each shape, while the
`display()` method is shared across all shapes.
4 To demonstrate runtime polymorphism in Java, we can create a base class `Animal` with a method `makeSound()`. Then, we can create three subclasses (`Dog`, `Cat`, and
`Cow`) that override the `makeSound()` method. Finally, we can store objects of these subclasses in an array of type `Animal` and call their `makeSound()` methods

```java

// Base class Animal

class Animal {

// Method to make a sound

public void makeSound() {

System.out.println("Animal makes a sound.");

// Subclass Dog

class Dog extends Animal {

// Override makeSound() method

@Override

public void makeSound() {

System.out.println("Woof!");

// Subclass Cat

class Cat extends Animal {

// Override makeSound() method

@Override

public void makeSound() {

System.out.println("Meow!");

// Subclass Cow

class Cow extends Animal {

// Override makeSound() method

@Override

public void makeSound() {

System.out.println("Moo!");
}

// Main class to demonstrate polymorphism

public class PolymorphismExample {

public static void main(String[] args) {

// Create an array of Animal objects

Animal[] animals = new Animal[3];

// Store objects of Dog, Cat, and Cow in the array

animals[0] = new Dog();

animals[1] = new Cat();

animals[2] = new Cow();

// Call makeSound() for each object

for (Animal animal : animals) {

animal.makeSound(); // Runtime polymorphism

**Base Class (`Animal`)**:

- The `Animal` class has a method `makeSound()` that prints `"Animal makes a sound."`.

**Subclasses (`Dog`, `Cat`, `Cow`)**:

- Each subclass overrides the `makeSound()` method to provide its specific sound:

- `Dog` prints `"Woof!"`.

- `Cat` prints `"Meow!"`.

- `Cow` prints `"Moo!"`.

**Polymorphism**:

- In the `main` method, we create an array of type `Animal` and store objects of `Dog`, `Cat`, and `Cow` in it.

- When we iterate through the array and call `makeSound()`, the overridden method in each subclass is executed at runtime. This is runtime polymorphism.

Output
When you run the program, the output will be

Woof!

Meow!

Moo!

This demonstrates how polymorphism allows the correct `makeSound()` method to be called based on the actual object type at runtime.

5. Employee Management System

```java

// Abstract class Employee

abstract class Employee {

private String name;

private int employeeId;

// Constructor

public Employee(String name, int employeeId) {

this.name = name;

this.employeeId = employeeId;

// Abstract method

public abstract double calculateSalary();

// Non-abstract method

public void displayDetails() {

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

System.out.println("Employee ID: " + employeeId);

// Subclass FullTimeEmployee

class FullTimeEmployee extends Employee {

private double monthlySalary;

// Constructor

public FullTimeEmployee(String name, int employeeId, double monthlySalary) {

super(name, employeeId);

this.monthlySalary = monthlySalary;

// Implement calculateSalary()

@Override
public double calculateSalary() {

return monthlySalary;

// Override displayDetails()

@Override

public void displayDetails() {

super.displayDetails();

System.out.println("Monthly Salary: " + monthlySalary);

System.out.println("Calculated Salary: " + calculateSalary());

// Subclass PartTimeEmployee

class PartTimeEmployee extends Employee {

private int hoursWorked;

private double hourlyRate;

// Constructor

public PartTimeEmployee(String name, int employeeId, int hoursWorked, double hourlyRate) {

super(name, employeeId);

this.hoursWorked = hoursWorked;

this.hourlyRate = hourlyRate;

// Implement calculateSalary()

@Override

public double calculateSalary() {

return hoursWorked * hourlyRate;

// Override displayDetails()

@Override

public void displayDetails() {

super.displayDetails();

System.out.println("Hours Worked: " + hoursWorked);

System.out.println("Hourly Rate: " + hourlyRate);

System.out.println("Calculated Salary: " + calculateSalary());


}

// Main class to demonstrate

public class Main {

public static void main(String[] args) {

// Create objects

Employee fullTimeEmp = new FullTimeEmployee("John Doe", 101, 5000);

Employee partTimeEmp = new PartTimeEmployee("Jane Smith", 102, 20, 15);

// Demonstrate abstraction, inheritance, and polymorphism

Employee[] employees = {fullTimeEmp, partTimeEmp};

for (Employee emp : employees) {

emp.displayDetails();

System.out.println(); // For spacing

6. Advanced Polymorphism

```java

// Interface Playable

interface Playable {

void play();

// Class Football

class Football implements Playable {

@Override

public void play() {

System.out.println("Playing football");

// Class Guitar

class Guitar implements Playable {

@Override

public void play() {

System.out.println("Playing guitar");
}

// Class VideoGame

class VideoGame implements Playable {

@Override

public void play() {

System.out.println("Playing video game");

// Main class to demonstrate

public class Main {

public static void main(String[] args) {

// Create objects

Playable football = new Football();

Playable guitar = new Guitar();

Playable videoGame = new VideoGame();

// Use polymorphism

Playable[] playables = {football, guitar, videoGame};

for (Playable playable : playables) {

playable.play();

7. Encapsulation + Inheritance

```java

// Class Person

class Person {

private String name;

private int age;

// Constructor

public Person(String name, int age) {

this.name = name;

this.age = age;

}
// Getters and Setters

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

public void setAge(int age) {

this.age = age;

// Display details

public void displayDetails() {

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

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

// Subclass Student

class Student extends Person {

private String studentId;

private String grade;

// Constructor

public Student(String name, int age, String studentId, String grade) {

super(name, age);

this.studentId = studentId;

this.grade = grade;

// Getters and Setters

public String getStudentId() {

return studentId;

}
public void setStudentId(String studentId) {

this.studentId = studentId;

public String getGrade() {

return grade;

public void setGrade(String grade) {

this.grade = grade;

// Override displayDetails()

@Override

public void displayDetails() {

super.displayDetails();

System.out.println("Student ID: " + studentId);

System.out.println("Grade: " + grade);

// Main class to demonstrate

public class Main {

public static void main(String[] args) {

// Create object

Student student = new Student("Alice", 20, "S12345", "A");

student.displayDetails();

// Demonstrate encapsulation

student.setName("Alice Smith");

student.setAge(21);

student.setGrade("B");

System.out.println("\nAfter updating details:");

student.displayDetails();

Here’s the implementation of the tasks using **Java**:

8. Abstraction and Polymorphism with Instrument Class


```java

// Abstract class Instrument

abstract class Instrument {

// Abstract method

public abstract void play();

// Non-abstract method

public void tune() {

System.out.println("Tuning the instrument.");

// Subclass Piano

class Piano extends Instrument {

@Override

public void play() {

System.out.println("Playing piano");

// Subclass Violin

class Violin extends Instrument {

@Override

public void play() {

System.out.println("Playing violin");

// Subclass Flute

class Flute extends Instrument {

@Override

public void play() {

System.out.println("Playing flute");

//

}Output

Tuning the instrument.


Playing piano

Tuning the instrument.

Playing violin

Tuning the instrument.

Playing flute

9. Real-World Scenario: Payment System

```java

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

// Abstract class Payment

abstract class Payment {

protected double amount;

protected String paymentDate;

public Payment(double amount) {

this.amount = amount;

this.paymentDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

// Abstract method

public abstract void processPayment();

// Non-abstract method

public void displayPaymentDetails() {

System.out.println("Amount: $" + amount + ", Payment Date: " + paymentDate);

// Subclass CreditCardPayment

class CreditCardPayment extends Payment {

private String cardNumber;

private String expiryDate;

public CreditCardPayment(double amount, String cardNumber, String expiryDate) {

super(amount);

this.cardNumber = cardNumber;

this.expiryDate = expiryDate;

@Override
public void processPayment() {

System.out.println("Processing credit card payment of $" + amount + " with card number " + cardNumber);

// Subclass PayPalPayment

class PayPalPayment extends Payment {

private String email;

public PayPalPayment(double amount, String email) {

super(amount);

this.email = email;

@Override

public void processPayment() {

System.out.println("Processing PayPal payment of $" + amount + " from " + email);

// Subclass CashPayment

class CashPayment extends Payment {

public CashPayment(double amount) {

super(amount);

@Override

public void processPayment() {

System.out.println("Processing cash payment of $" + amount);

// Main class

public class Main {

public static void main(String[] args) {

// Polymorphism: Array of Payment objects

Payment[] payments = {

new CreditCardPayment(100, "1234-5678-9012-3456", "12/25"),

new PayPalPayment(200, "[email protected]"),

new CashPayment(50)
};

for (Payment payment : payments) {

payment.displayPaymentDetails();

payment.processPayment();

System.out.println();

Output

Amount: $100.0, Payment Date: 2025-03-05 12:34:56

Processing credit card payment of $100.0 with card number 1234-5678-9012-3456

Amount: $200.0, Payment Date: 2025-03-05 12:34:56

Processing PayPal payment of $200.0 from [email protected]

Amount: $50.0, Payment Date: 2025-03-05 12:34:56

Processing cash payment of $50.0

10. Challenge Question: Shape System

```java

// Interface Drawable

interface Drawable {

void draw();

// Abstract class Shape

abstract class Shape {

protected String color;

public Shape(String color) {

this.color = color;

// Abstract method

public abstract double calculateArea();

// Non-abstract method

public void displayColor() {

System.out.println("Color: " + color);

}
// Subclass Circle

class Circle extends Shape implements Drawable {

private double radius;

public Circle(String color, double radius) {

super(color);

this.radius = radius;

@Override

public double calculateArea() {

return Math.PI * radius * radius;

@Override

public void draw() {

System.out.println("Drawing a " + color + " circle with radius " + radius);

// Subclass Rectangle

class Rectangle extends Shape implements Drawable {

private double width;

private double height;

public Rectangle(String color, double width, double height) {

super(color);

this.width = width;

this.height = height;

@Override

public double calculateArea() {

return width * height;

@Override

public void draw() {

System.out.println("Drawing a " + color + " rectangle with width " + width + " and height " + height);

}
}

// Main class

public class Main {

public static void main(String[] args) {

// Polymorphism: Array of Shape objects

Shape[] shapes = {

new Circle("Red", 5),

new Rectangle("Blue", 4, 6)

};

for (Shape shape : shapes) {

shape.displayColor();

System.out.println("Area: " + shape.calculateArea());

if (shape instanceof Drawable) {

((Drawable) shape).draw();

System.out.println();

Output

Color: Red

Area: 78.53981633974483

Drawing a Red circle with radius 5.0

Color: Blue

Area: 24.0

Drawing a Blue rectangle with width 4.0 and height 6.0

You might also like