Oop Assignment
Oop Assignment
Id no mdr/1634/19
department SE
Key concept
-|nheritance Create new classes from existing ones to reuse and extend functionality.
1 Java implementation of the class hierarchy for the Vehicle system, along with the creation of objects for `Car` and `Motorcycle` to demonstrate inheritance
class Vehicle {
// Constructor
this.make = make;
this.model = model;
this.year = year;
// Methods
System.out.println("Vehicle Details: " + year + " " + make + " " + model);
// Constructor
@Override
// Constructor
this.hasSideCar = hasSideCar;
@Override
car.start();
car.displayDetails();
car.stop();
motorcycle.start();
motorcycle.displayDetails();
motorcycle.stop();
Output:
Number of Doors: 4
**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
// Constructor
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
if (amount > 0) {
this.balance += amount;
} else {
if (amount > 0) {
this.balance -= amount;
} else {
System.out.println("Insufficient balance.");
} else {
return this.balance;
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:
Balance: $1000.0
Deposited: $500.0
Withdrew: $200.0
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.
```java
System.out.println("This is a shape.");
// Subclass Circle
this.radius = radius;
@Override
// Subclass Rectangle
this.length = length;
this.width = width;
@Override
circle.display();
rectangle.display();
**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:**
Output:
This is a shape.
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
class Animal {
// Subclass Dog
@Override
System.out.println("Woof!");
// Subclass Cat
@Override
System.out.println("Meow!");
// Subclass Cow
@Override
System.out.println("Moo!");
}
- The `Animal` class has a method `makeSound()` that prints `"Animal makes a sound."`.
- Each subclass overrides the `makeSound()` method to provide its specific sound:
**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.
```java
// Constructor
this.name = name;
this.employeeId = employeeId;
// Abstract method
// Non-abstract method
// Subclass FullTimeEmployee
// Constructor
super(name, employeeId);
this.monthlySalary = monthlySalary;
// Implement calculateSalary()
@Override
public double calculateSalary() {
return monthlySalary;
// Override displayDetails()
@Override
super.displayDetails();
// Subclass PartTimeEmployee
// Constructor
super(name, employeeId);
this.hoursWorked = hoursWorked;
this.hourlyRate = hourlyRate;
// Implement calculateSalary()
@Override
// Override displayDetails()
@Override
super.displayDetails();
// Create objects
emp.displayDetails();
6. Advanced Polymorphism
```java
// Interface Playable
interface Playable {
void play();
// Class Football
@Override
System.out.println("Playing football");
// Class Guitar
@Override
System.out.println("Playing guitar");
}
// Class VideoGame
@Override
// Create objects
// Use polymorphism
playable.play();
7. Encapsulation + Inheritance
```java
// Class Person
class Person {
// Constructor
this.name = name;
this.age = age;
}
// Getters and Setters
return name;
this.name = name;
return age;
this.age = age;
// Display details
// Subclass Student
// Constructor
super(name, age);
this.studentId = studentId;
this.grade = grade;
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
return grade;
this.grade = grade;
// Override displayDetails()
@Override
super.displayDetails();
// Create object
student.displayDetails();
// Demonstrate encapsulation
student.setName("Alice Smith");
student.setAge(21);
student.setGrade("B");
student.displayDetails();
// Abstract method
// Non-abstract method
// Subclass Piano
@Override
System.out.println("Playing piano");
// Subclass Violin
@Override
System.out.println("Playing violin");
// Subclass Flute
@Override
System.out.println("Playing flute");
//
}Output
Playing violin
Playing flute
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
this.amount = amount;
// Abstract method
// Non-abstract method
// Subclass CreditCardPayment
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
super(amount);
this.email = email;
@Override
// Subclass CashPayment
super(amount);
@Override
// Main class
Payment[] payments = {
new CashPayment(50)
};
payment.displayPaymentDetails();
payment.processPayment();
System.out.println();
Output
```java
// Interface Drawable
interface Drawable {
void draw();
this.color = color;
// Abstract method
// Non-abstract method
}
// Subclass Circle
super(color);
this.radius = radius;
@Override
@Override
// Subclass Rectangle
super(color);
this.width = width;
this.height = height;
@Override
@Override
System.out.println("Drawing a " + color + " rectangle with width " + width + " and height " + height);
}
}
// Main class
Shape[] shapes = {
new Rectangle("Blue", 4, 6)
};
shape.displayColor();
((Drawable) shape).draw();
System.out.println();
Output
Color: Red
Area: 78.53981633974483
Color: Blue
Area: 24.0