Week 5 Practice Questions - Object Oriented
Programming Paradigm
    1. Abstraction
      Qn 1: Create an abstract class Animal with abstract methods make Sound() and
      eat().Create subclasses Dog, Cat, and Bird that inherit from Animal and
      implement the abstract
      methods accordingly.
abstract class Animal
{
    public abstract void sound();
    public abstract void eat();
}
class Dog extends Animal
{
    public void sound()
    {
        System.out.println("Barking");
    }
    public void eat()
    {
        System.out.println("Dog is eating");
    }
}
class Cat extends Animal
{
    public void sound()
    {
        System.out.println("Meowing");
    }
    public void eat()
    {
        System.out.println("Cat is eating");
    }
}
class Bird extends Animal
{
    public void sound()
    {
        System.out.println("Chirping");
    }
    public void eat()
    {
        System.out.println("Bird is eating");
    }
}
public class Animals
{
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        Bird bird = new Bird();
        dog.sound();
        dog.eat();
        cat.sound();
        cat.eat();
        bird.sound();
        bird.eat();
    }
}
        Output:
        Qn 2: Create an abstract class Shape with abstract methods calculateArea()
        and calculatePerimeter(). Create subclasses Circle, Rectangle, and Triangle
        that inherit from
        Shape and implement the abstract methods accordingly.
abstract class Shape
{
    public abstract double Area();
    public abstract double Perimeter();
}
class Circle extends Shape
{
    int radius;
    Circle(int r)
     {
          radius = r;
     }
     public double Area()
     {
          return radius*radius;
     }
     public double Perimeter()
     {
          return 2*3.14*radius;
     }
}
class Rectangle extends Shape
{
     int length,width; Rectangle(int
     l,int w)
     {
           length = l;
           width = w;
     }
     public double Area()
     {
           return length*width;
     }
     public double Perimeter()
     {
           return 2*(length+width);
     }
}
class Triangle extends Shape
{
     int height,base,side1,side2; Triangle(int h,int
     b,int s1,int s2)
     {
           height=h;
           base=b;
           side1=s1;
           side2=s2;
     }
     public double Area()
     {
           return (height*base)/2;
     }
     public double Perimeter()
     {
           return base+side1+side2;
    }
}
public class Shapes
{
    public static void main(String args[])
    {
        Circle c=new Circle(5);
        System.out.println("Area of Circle: "+c.Area());
        System.out.println("Perimeter of Circle: "+c.Perimeter());
        Rectangle r=new Rectangle(5,6);
        System.out.println("Area of Rectangle: "+r.Area());
        System.out.println("Perimeter of Rectangle: "+r.Perimeter());
        Triangle t= new Triangle(10, 8, 7, 6);
        System.out.println("Area of Triangle: "+t.Area());
        System.out.println("Perimeter of Triangle: "+t.Perimeter());
    }
}
        Output:
        Qn 3: Create an abstract class Employee with abstract methods
        calculateSalary() andgetEmployeeDetails(). Create subclasses
        RegularEmployee, ContractEmployee, and HourlyEmployee that inherit from
        Employee and implement the abstract methods Accordingly
abstract class Employee {
    String name;
    int id;
    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }
    abstract double calculateSalary();
    abstract String getEmployeeDetails();
}
class RegularEmployee extends Employee {
     double basicSalary;
     double bonus;
    public RegularEmployee(String name, int id, double basicSalary, doublebonus) {
         super(name, id); this.basicSalary =
         basicSalary;this.bonus = bonus;
    }
    @Override
    double calculateSalary() { return
        basicSalary + bonus;
    }
    @Override
    String getEmployeeDetails() {
         return "Regular Employee: " + name + ", ID: " + id + ", Salary: " +calculateSalary();
    }
}
class ContractEmployee extends Employee {double
     contractAmount;
    public ContractEmployee(String name, int id, double contractAmount) {super(name,
         id);
         this.contractAmount = contractAmount;
    }
    @Override
    double calculateSalary() {return
        contractAmount;
    }
    @Override
    String getEmployeeDetails() {
          return "Contract Employee: " + name + ", ID: " + id + ", ContractAmount: " +
calculateSalary();
     }
}
class HourlyEmployee extends Employee {
     double hourlyRate;
     int hoursWorked;
    public HourlyEmployee(String name, int id, double hourlyRate, int
hoursWorked) {
         super(name, id); this.hourlyRate =
         hourlyRate; this.hoursWorked =
         hoursWorked;
    }
    @Override
    double calculateSalary() {
        return hourlyRate * hoursWorked;
    }
    @Override
    String getEmployeeDetails() {
         return "Hourly Employee: " + name + ", ID: " + id + ", Hours Worked: "
+ hoursWorked + ", Salary: " + calculateSalary();
    }
}
public class Employees {
     public static void main(String[] args) {
          Employee regEmp = new RegularEmployee("John Mark", 101, 50000, 5000);
          Employee contEmp = new ContractEmployee("Jane Smith", 102, 60000); Employee
          hourEmp = new HourlyEmployee("Mark Johnson", 103, 50, 160);
         System.out.println(regEmp.getEmployeeDetails());
         System.out.println(contEmp.getEmployeeDetails());
         System.out.println(hourEmp.getEmployeeDetails());
    }
}
        Output:
      II. Polymorphism
      Qn 1: Create a hierarchy of animals with classes like Animal, Mammal, Bird,
      and Fish. Implement polymorphism to demonstrate different animal sounds.
      Hint:
      Create an abstract class Animal with an abstract method makeSound().
      Create subclasses Mammal, Bird, and Fish, inheriting from Animal and
      overriding the makeSound() method.
      Create an array of Animal objects to store different types of animals.
      Iterate through the array and call the makeSound() method for each animal,
      demonstrating polymorphism.
abstract class Animal {
    String name;
    public Animal(String name) {
        this.name = name;
    }
    abstract void makeSound();
}
class Mammal extends Animal {
    public Mammal(String name) {
        super(name);
    }
    @Override
    void makeSound() {
         System.out.println(name + " says: Roar!");
    }
}
class Bird extends Animal {
    public Bird(String name) {
         super(name);
    }
    @Override
    void makeSound() {
         System.out.println(name + " says: Tweet!");
    }
}
class Fish extends Animal {
    public Fish(String name) {
         super(name);
    }
    @Override
    void makeSound() {
         System.out.println(name + " says: Blub!");
    }
}
public class Animals {
     public static void main(String[] args) {Animal[]
          animals = new Animal[3]; animals[0] = new
          Mammal("Lion"); animals[1] = new
          Bird("Sparrow"); animals[2] = new
          Fish("Goldfish");
         for (Animal animal : animals) {
              animal.makeSound();
         }
    }
}
      Output:
      Qn 2: Overload
      Create a Calculator class with multiple calculate () methods that take different
      combinations of arguments (e.g., calculate (int, int), calculate (double,
      double), calculate (int, int, char)). Implement these methods to perform
      different arithmeticoperations based on the arguments.
public class Calculator {
    public int calculate(int a, int b) {
        return a + b;
    }
    public double calculate(double a, double b) {
        return a + b;
    }
    public int calculate(int a, int b, char operator) {
        switch (operator) {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                if (b != 0) {
                     return a / b;
                } else {
                     throw new ArithmeticException("Division by zero is not
allowed.");
                }
            default:
                throw new IllegalArgumentException("Invalid operator");
        }
    }
    public static void main(String[] args) {
        Calculator calc = new Calculator();
         System.out.println("Sum of 10 and 20 (int): " + calc.calculate(10,
20));
        System.out.println("Sum of 5.5 and 2.3 (double): " +
calc.calculate(5.5, 2.3));
        System.out.println("Product of 10 and 20 (int with operator): " +
calc.calculate(10, 20, '*'));
        System.out.println("Division of 10 and 2 (int with operator): " +
calc.calculate(10, 2, '/'));
    }
}
        Output:
        Qn 3: Override
        Create a base class Calculator with a calculate () method that takes two double
        arguments.
        Implement this method to perform addition. Create subclasses SubtractionCalculator,
        MultiplicationCalculator, and DivisionCalculator that inherit from Calculator
        andoverride
        the calculate () method to perform their respective arithmetic operations.
class Calculator {
    public double calculate(double a, double b) {
        return a + b;
    }
}
class SubtractionCalculator extends Calculator {
     @Override
     public double calculate(double a, double b) {return a -
          b;
     }
}
class MultiplicationCalculator extends Calculator {
     @Override
     public double calculate(double a, double b) {return a *
          b;
     }
}
class DivisionCalculator extends Calculator {
     @Override
     public double calculate(double a, double b) {if (b != 0) {
                return a / b;
          } else {
                throw new ArithmeticException("Division by zero is not allowed.");
          }
     }
}
public class Calculators {
     public static void main(String[] args) { Calculator
          addCalc = new Calculator();
          Calculator subCalc = new SubtractionCalculator(); Calculator
          mulCalc = new MultiplicationCalculator();Calculator divCalc =
          new DivisionCalculator();
          System.out.println("Addition: " + addCalc.calculate(10, 5));
          System.out.println("Subtraction: " + subCalc.calculate(10, 5));
          System.out.println("Multiplication: " + mulCalc.calculate(10, 5));
          System.out.println("Division: " + divCalc.calculate(10, 5));
    }
}
        Output:
        III. Inheritance
        Qn 1: Base Class: Animal
        ➢ Attributes: name, sound, num_legs
        ➢ Methods: make_sound(),
        walk() Derived Classes:
        ➢ Dog: barks
        ➢ Cat: meows
        ➢ Bird: chirps,
        fliesQuestions:
        1. Create a base class Animal with the specified attributes and methods.
        2. Create derived classes Dog, Cat, and Bird that inherit from Animal.
        3. Override the make_sound() and walk() methods in each derived class to
        providespecific
        implementations.
        4. Create objects of each derived class and demonstrate their behavior
        (e.g., call make_sound() and walk() methods).
// Base class Animal
class Animal {
    String name;
    String sound;
    int num_legs;
    // Constructor
    public Animal(String name, String sound, int num_legs) {this.name =
         name;
         this.sound = sound; this.num_legs =
         num_legs;
    }
    // Method to make sound public
    void make_sound() {
         System.out.println(name + " makes a sound: " + sound);
    }
    // Method to walk public
    void walk() {
         System.out.println(name + " walks on " + num_legs + " legs.");
    }
}
// Subclass Dog
class Dog extends Animal {
    // Constructor
    public Dog(String name) { super(name,
         "barks", 4);
    }
    // Override make_sound() method
    @Override
    public void make_sound() {
         System.out.println(name + " barks: Woof Woof!");
    }
    // Override walk() method
    @Override
    public void walk() {
         System.out.println(name + " walks on " + num_legs + " legs, waggingits tail.");
    }
}
// Subclass Cat
class Cat extends Animal {
    // Constructor
    public Cat(String name) { super(name,
         "meows", 4);
    }
    // Override make_sound() method
    @Override
    public void make_sound() {
         System.out.println(name + " meows: Meow Meow!");
    }
    // Override walk() method
    @Override
    public void walk() {
         System.out.println(name + " walks gracefully on " + num_legs + "legs.");
    }
}
// Subclass Bird
class Bird extends Animal {
    // Constructor
    public Bird(String name) { super(name,
         "chirps", 2);
    }
    // Override make_sound() method
    @Override
    public void make_sound() {
         System.out.println(name + " chirps: Tweet Tweet!");
    }
    // Override walk() method
    @Override
    public void walk() {
         System.out.println(name + " hops on " + num_legs + " legs andflies.");
    }
}
// Main class to test the implementationpublic
class Animals {
     public static void main(String[] args) {
          // Create objects of derived classesAnimal
          dog = new Dog("Buddy"); Animal cat = new
          Cat("Whiskers"); Animal bird = new
          Bird("Tweety");
         // Demonstrate behavior
         dog.make_sound();
         dog.walk();
         cat.make_sound();
         cat.walk();
         bird.make_sound();
         bird.walk();
    }
}
        Output:
        Qn 2: Consider a vehicle hierarchy with a base class Vehicle that has attributes
        like make,
        model, year, and num_wheels. We want to create derived classes Car, Truck,
        andMotorcycle
        that inherit from Vehicle and have additional specific attributes and methods.
        Additionally, we
        want to introduce another base class Engine with attributes like type,
        horsepower, and
        fuel_type, and have Car, Truck, and Motorcycle inherit from both Vehicle and
        Engine.Implement using multiple inheritance.
class Vehicle {
    String make;
    String model;
    int year;
    int num_wheels;
    public Vehicle(String make, String model, int year, int num_wheels) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.num_wheels = num_wheels;
    }
    public void displayVehicleInfo() { System.out.println("Make: " + make);
         System.out.println("Model: " + model); System.out.println("Year: "
         + year); System.out.println("Number of Wheels: " + num_wheels);
    }
}
interface Engine { String
     getType(); int
     getHorsepower();
     String getFuelType();
}
class Car extends Vehicle implements Engine {String
     engineType;
     int horsepower;
     String fuelType;int
     numDoors;
    public Car(String make, String model, int year, int num_wheels, StringengineType, int
horsepower, String fuelType, int numDoors) {
         super(make, model, year, num_wheels);
         this.engineType = engineType;
         this.horsepower = horsepower; this.fuelType
         = fuelType; this.numDoors = numDoors;
    }
    @Override
    public String getType() {return
         engineType;
    }
    @Override
    public int getHorsepower() {return
         horsepower;
    }
    @Override
    public String getFuelType() {return
         fuelType;
    }
    public void displayCarInfo() {
         displayVehicleInfo();
         System.out.println("Engine Type: " + getType());
         System.out.println("Horsepower: " + getHorsepower());
         System.out.println("Fuel Type: " + getFuelType());
         System.out.println("Number of Doors: " + numDoors);
    }
}
class Truck extends Vehicle implements Engine {String
     engineType;
     int horsepower;
     String fuelType; int
     loadCapacity;
    public Truck(String make, String model, int year, int num_wheels, StringengineType, int
horsepower, String fuelType, int loadCapacity) {
         super(make, model, year, num_wheels);
         this.engineType = engineType;
         this.horsepower = horsepower; this.fuelType
         = fuelType; this.loadCapacity = loadCapacity;
    }
    @Override
    public String getType() {return
         engineType;
    }
    @Override
    public int getHorsepower() {return
         horsepower;
    }
    @Override
    public String getFuelType() {return
         fuelType;
    }
    public void displayTruckInfo() {
         displayVehicleInfo();
         System.out.println("Engine Type: " + getType()); System.out.println("Horsepower: " +
         getHorsepower()); System.out.println("Fuel Type: " + getFuelType());
         System.out.println("Load Capacity: " + loadCapacity + " kg");
     }
}
class Motorcycle extends Vehicle implements Engine {String
     engineType;
     int horsepower; String
     fuelType; boolean
     hasSidecar;
     public Motorcycle(String make, String model, int year, int num_wheels,String
engineType, int horsepower, String fuelType, boolean hasSidecar) {
          super(make, model, year, num_wheels);
          this.engineType = engineType;
          this.horsepower = horsepower; this.fuelType
          = fuelType; this.hasSidecar = hasSidecar;
     }
     @Override
     public String getType() {return
          engineType;
     }
     @Override
     public int getHorsepower() {return
          horsepower;
     }
     @Override
     public String getFuelType() {return
          fuelType;
     }
     public void displayMotorcycleInfo() {
          displayVehicleInfo();
          System.out.println("Engine Type: " + getType()); System.out.println("Horsepower: " +
          getHorsepower()); System.out.println("Fuel Type: " + getFuelType());
          System.out.println("Has Sidecar: " + (hasSidecar ? "Yes" : "No"));
     }
}
public class Vehicles {
     public static void main(String[] args) {
           Car car = new Car("Toyota", "Corolla", 2020, 4, "V6", 300, "Petrol",
4);
           Truck truck = new Truck("Ford", "F-150", 2019, 4, "V8", 400, "Diesel",
1000);
        Motorcycle motorcycle = new Motorcycle("Harley-Davidson", "Iron 883",
2021, 2, "V-Twin", 70, "Petrol", false);
           System.out.println("Car Details:");
           car.displayCarInfo();
           System.out.println("\nTruck Details:");
           truck.displayTruckInfo();
           System.out.println("\nMotorcycle Details:");
           motorcycle.displayMotorcycleInfo();
      }
}
          Output:
          IV. Encapsulation
          Qn 1: A bank wants to create a class to represent bank accounts. Each
          accountshould have a
      unique account number, an initial balance, and methods to deposit and
      withdrawfunds. The
      bank wants to ensure that the account balance is always positive and that
      withdrawals do not
      exceed the balance.
      ➢ Create a class named BankAccount with private attributes for
      accountNumber, balance,
      and a constant for the minimum balance allowed.
      ➢ Implement public getter and setter methods for the accountNumber attribute.
      ➢ Implement public methods deposit and withdraw that update the
      balanceappropriately,
      ensuring that the balance remains positive and that withdrawals do not exceed
      the balance.
class BankAccount {
    // Private attributes
    private String accountNumber;
    private double balance;
    private static final double MIN_BALANCE = 0.0;      // Minimum balance allowed
    // Constructor
    public BankAccount(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        if (initialBalance >= MIN_BALANCE) {
            this.balance = initialBalance;
        } else {
            throw new IllegalArgumentException("Initial balance cannot be
negative.");
        }
    }
    // Public getter for accountNumber
    public String getAccountNumber() {
        return accountNumber;
    }
    // Public setter for accountNumber
    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }
     // Public method to deposit funds public
     void deposit(double amount) {
           if (amount > 0) { balance
                 += amount;
                 System.out.println("Deposited: $" + amount + ". New balance: $" +
balance);
           } else {
                 throw new IllegalArgumentException("Deposit amount must be
positive.");
           }
     }
     // Public method to withdraw funds public
     void withdraw(double amount) {
           if (amount > 0) {
                 if (balance - amount >= MIN_BALANCE) {
                       balance -= amount;
                       System.out.println("Withdrew: $" + amount + ". New balance: $"
+ balance);
                 } else {
                       System.out.println("Insufficient funds. Withdrawal denied.");
                 }
           } else {
                 throw new IllegalArgumentException("Withdrawal amount must be
positive.");
           }
     }
    // Public getter for balancepublic
    double getBalance() {
         return balance;
    }
}
public class Bank {
     public static void main(String[] args) {
          // Create a new bank account with an initial balance
          BankAccount account = new BankAccount("123456789", 500.00);
         // Display account details
         System.out.println("Account Number: " + account.getAccountNumber());
         System.out.println("Initial Balance: $" + account.getBalance());
         // Deposit funds
         account.deposit(150.00);
         // Withdraw funds
         account.withdraw(200.00);
         // Attempt to withdraw more funds than available
         account.withdraw(600.00);
         // Display final balance
         System.out.println("Final Balance: $" + account.getBalance());
    }
}
        Output:
        Qn 2: Write a Java program to create a class called Rectangle with private
        instancevariables
        length and width. Provide public getter and setter methods to access and
        modifythese
        variables.
class Rectangle {
    // Private instance variables
    private double length;
    private double width;
    // Constructor to initialize the length and width
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }
    // Default constructor
    public Rectangle() {
        this.length = 0.0;
        this.width = 0.0;
    }
    // Getter for length
    public double getLength() {return
         length;
    }
    // Setter for length
    public void setLength(double length) {if
         (length > 0) {
               this.length = length;
         } else {
               System.out.println("Length must be positive.");
         }
    }
    // Getter for width
    public double getWidth() {
         return width;
    }
    // Setter for width
    public void setWidth(double width) {if
         (width > 0) {
               this.width = width;
         } else {
               System.out.println("Width must be positive.");
         }
    }
    // Method to calculate the area of the rectanglepublic
    double calculateArea() {
        return length * width;
    }
    // Method to calculate the perimeter of the rectanglepublic
    double calculatePerimeter() {
        return 2 * (length + width);
    }
    // Method to display the details of the rectanglepublic void
    displayRectangleInfo() {
         System.out.println("Length: " + length); System.out.println("Width: " +
         width); System.out.println("Area: " + calculateArea());
         System.out.println("Perimeter: " + calculatePerimeter());
    }
}
public class Rectangles {
    public static void main(String[] args) {
        // Create a Rectangle object using the parameterized constructor
        Rectangle rect1 = new Rectangle(5.0, 3.0);
        rect1.displayRectangleInfo();
         // Modify the length and width using setter methods
         rect1.setLength(7.5);
         rect1.setWidth(4.0);
         System.out.println("\nAfter modifying length and width:");
         rect1.displayRectangleInfo();
         // Create a Rectangle object using the default constructor
         Rectangle rect2 = new Rectangle();
         System.out.println("\nDefault Rectangle:");
         rect2.displayRectangleInfo();
         // Set length and width for the default rectangle
         rect2.setLength(6.0);
         rect2.setWidth(2.5);
         System.out.println("\nAfter setting length and width:");
         rect2.displayRectangleInfo();
    }
}
        Output:
                  Rohit N Rajput
                  RA2311033010119
                  AK-2