Assignments For Class 19 - Introduction to Object-Oriented Programming (OOP) - Part 1

Rashmi Mishra
0

Assignments For  Class 19 - Introduction to Object-Oriented Programming (OOP) - Part 1

Assignments on Object-Oriented Programming (OOP) in PHP

Here are some assignments focusing on the concepts of classes, objects, encapsulation, and basic OOP principles, along with solutions and explanations.


Assignment 1: Creating a Class and Object

Task: Create a class named Student with the following properties:

  • name (string)
  • age (integer)
  • grade (string)

Implement the following methods:

  • setDetails($name, $age, $grade): Sets the values of the properties.
  • getDetails(): Returns the details of the student as a formatted string.

Solution:

php

Copy code

class Student {

    private $name;

    private $age;

    private $grade;

 

    public function setDetails($name, $age, $grade) {

        $this->name = $name;

        $this->age = $age;

        $this->grade = $grade;

    }

 

    public function getDetails() {

        return "Name: " . $this->name . ", Age: " . $this->age . ", Grade: " . $this->grade;

    }

}

 

// Creating an object of Student

$student1 = new Student();

$student1->setDetails("Alice", 20, "A");

echo $student1->getDetails(); // Output: Name: Alice, Age: 20, Grade: A

Explanation:

  • The Student class encapsulates the properties name, age, and grade as private.
  • The setDetails method allows external code to set these properties, while the getDetails method retrieves and formats the data.
  • The object $student1 is created and used to demonstrate the methods.

Assignment 2: Encapsulation and Method Overriding

Task: Create a class named Animal with a method sound() that returns "Some sound". Then, create a derived class named Cat that overrides the sound() method to return "Meow".

Solution:

php

Copy code

class Animal {

    public function sound() {

        return "Some sound";

    }

}

 

class Cat extends Animal {

    public function sound() {

        return "Meow";

    }

}

 

// Creating objects

$animal = new Animal();

echo $animal->sound(); // Output: Some sound

 

$cat = new Cat();

echo $cat->sound(); // Output: Meow

Explanation:

  • The Animal class defines a sound() method.
  • The Cat class inherits from Animal and overrides the sound() method to provide a specific implementation.
  • This demonstrates polymorphism, where a method behaves differently based on the object calling it.

Assignment 3: Using Constructors

Task: Modify the Student class to include a constructor that initializes the properties name, age, and grade when creating an object.

Solution:

php

Copy code

class Student {

    private $name;

    private $age;

    private $grade;

 

    // Constructor

    public function __construct($name, $age, $grade) {

        $this->name = $name;

        $this->age = $age;

        $this->grade = $grade;

    }

 

    public function getDetails() {

        return "Name: " . $this->name . ", Age: " . $this->age . ", Grade: " . $this->grade;

    }

}

 

// Creating an object using the constructor

$student1 = new Student("Bob", 22, "B");

echo $student1->getDetails(); // Output: Name: Bob, Age: 22, Grade: B

Explanation:

  • The __construct method acts as a constructor for the Student class, allowing property initialization upon object creation.
  • This approach enhances code readability and eliminates the need for separate setter methods for initialization.

Assignment 4: Class with Visibility Modifiers

Task: Create a class named BankAccount with the following properties and methods:

  • Properties: accountNumber, balance (private).
  • Methods: __construct($accountNumber) to initialize accountNumber and deposit($amount) to add to the balance. Create a method getBalance() to return the current balance.

Solution:

php

Copy code

class BankAccount {

    private $accountNumber;

    private $balance;

 

    // Constructor

    public function __construct($accountNumber) {

        $this->accountNumber = $accountNumber;

        $this->balance = 0; // Initial balance

    }

 

    public function deposit($amount) {

        if ($amount > 0) {

            $this->balance += $amount;

        }

    }

 

    public function getBalance() {

        return $this->balance;

    }

}

 

// Creating an object of BankAccount

$account = new BankAccount("123456789");

$account->deposit(500);

echo $account->getBalance(); // Output: 500

Explanation:

  • The BankAccount class encapsulates accountNumber and balance properties, keeping balance private to protect it from external modification.
  • The deposit method adds money to the balance only if the amount is positive, demonstrating the principle of encapsulation by controlling how the internal state can be modified.

Assignment 5: Class Inheritance

Task: Create a base class called Shape with a method area() that returns "Area not defined". Then create two derived classes: Rectangle and Circle. Implement the area() method in both derived classes to calculate the area based on their respective formulas.

Solution:

php

Copy code

class Shape {

    public function area() {

        return "Area not defined";

    }

}

 

class Rectangle extends Shape {

    private $length;

    private $width;

 

    public function __construct($length, $width) {

        $this->length = $length;

        $this->width = $width;

    }

 

    public function area() {

        return $this->length * $this->width; // Area of Rectangle

    }

}

 

class Circle extends Shape {

    private $radius;

 

    public function __construct($radius) {

        $this->radius = $radius;

    }

 

    public function area() {

        return pi() * pow($this->radius, 2); // Area of Circle

    }

}

 

// Creating objects

$rectangle = new Rectangle(10, 5);

echo "Rectangle Area: " . $rectangle->area(); // Output: Rectangle Area: 50

 

$circle = new Circle(7);

echo "\nCircle Area: " . $circle->area(); // Output: Circle Area: 153.9380400259

Explanation:

  • The Shape class is a base class with a general area() method that can be overridden by derived classes.
  • The Rectangle and Circle classes extend Shape and provide specific implementations for the area() method, demonstrating polymorphism and method overriding.

Assignment 6: Abstract Classes

Task: Create an abstract class Vehicle with an abstract method fuelType(). Then, create two classes: Car and Bike that extend Vehicle and implement the fuelType() method to return their respective fuel types.

Solution:

php

Copy code

abstract class Vehicle {

    abstract public function fuelType();

}

 

class Car extends Vehicle {

    public function fuelType() {

        return "Petrol"; // Car fuel type

    }

}

 

class Bike extends Vehicle {

    public function fuelType() {

        return "Diesel"; // Bike fuel type

    }

}

 

// Creating objects

$car = new Car();

echo "Car Fuel Type: " . $car->fuelType(); // Output: Car Fuel Type: Petrol

 

$bike = new Bike();

echo "\nBike Fuel Type: " . $bike->fuelType(); // Output: Bike Fuel Type: Diesel

Explanation:

  • The Vehicle class is declared as abstract, meaning it cannot be instantiated directly. It contains an abstract method fuelType() that must be implemented by any derived class.
  • The Car and Bike classes provide their specific implementations of the fuelType() method, demonstrating the use of abstract classes and methods.

Assignment 7: Interfaces

Task: Define an interface Payable with a method calculatePay(). Create two classes Employee and Contractor that implement the Payable interface. Each class should define how to calculate pay.

Solution:

php

Copy code

interface Payable {

    public function calculatePay();

}

 

class Employee implements Payable {

    private $hourlyRate;

    private $hoursWorked;

 

    public function __construct($hourlyRate, $hoursWorked) {

        $this->hourlyRate = $hourlyRate;

        $this->hoursWorked = $hoursWorked;

    }

 

    public function calculatePay() {

        return $this->hourlyRate * $this->hoursWorked; // Pay calculation for Employee

    }

}

 

class Contractor implements Payable {

    private $fixedRate;

 

    public function __construct($fixedRate) {

        $this->fixedRate = $fixedRate;

    }

 

    public function calculatePay() {

        return $this->fixedRate; // Pay calculation for Contractor

    }

}

 

// Creating objects

$employee = new Employee(20, 40);

echo "Employee Pay: $" . $employee->calculatePay(); // Output: Employee Pay: $800

 

$contractor = new Contractor(1500);

echo "\nContractor Pay: $" . $contractor->calculatePay(); // Output: Contractor Pay: $1500

Explanation:

  • The Payable interface defines a contract for any class that implements it, requiring the implementation of the calculatePay() method.
  • Both Employee and Contractor classes provide their own calculations for pay, demonstrating polymorphism through interface implementation.

Assignment 8: Composition

Task: Create a class Library that contains an array of Book objects. The Book class should have properties for title and author, and a method to display book details. Implement methods in Library to add books and display all books.

Solution:

php

Copy code

class Book {

    private $title;

    private $author;

 

    public function __construct($title, $author) {

        $this->title = $title;

        $this->author = $author;

    }

 

    public function getDetails() {

        return "Title: " . $this->title . ", Author: " . $this->author;

    }

}

 

class Library {

    private $books = []; // Array to hold Book objects

 

    public function addBook(Book $book) {

        $this->books[] = $book; // Add book to the array

    }

 

    public function displayBooks() {

        foreach ($this->books as $book) {

            echo $book->getDetails() . "\n"; // Display each book's details

        }

    }

}

 

// Creating objects and using composition

$library = new Library();

$library->addBook(new Book("1984", "George Orwell"));

$library->addBook(new Book("The Great Gatsby", "F. Scott Fitzgerald"));

 

echo "Library Books:\n";

$library->displayBooks();

/*

Output:

Library Books:

Title: 1984, Author: George Orwell

Title: The Great Gatsby, Author: F. Scott Fitzgerald

*/

Explanation:

  • The Book class encapsulates details about each book, while the Library class uses composition to manage a collection of Book objects.
  • The addBook method allows adding new books, and displayBooks iterates through the collection to display their details.

Assignment 9: Static Properties and Methods

Task: Create a class Counter with a static property count and a static method increment(). The method should increment the count by 1 each time it is called. Add another static method getCount() to return the current count.

Solution:

php

Copy code

class Counter {

    private static $count = 0; // Static property

 

    public static function increment() {

        self::$count++; // Increment static property

    }

 

    public static function getCount() {

        return self::$count; // Return current count

    }

}

 

// Using static methods

Counter::increment();

Counter::increment();

echo "Current Count: " . Counter::getCount(); // Output: Current Count: 2

Explanation:

  • The Counter class demonstrates the use of static properties and methods. The increment method updates the static property count, which is shared among all instances of the class.
  • Static methods can be called without creating an instance of the class, showcasing their utility for maintaining global state.

Assignment 10: Error Handling in OOP

Task: Create a class Account that throws an exception if a negative amount is deposited. Implement a method deposit($amount) that handles this logic and throws an InvalidArgumentException if the amount is negative.

Solution:

php

Copy code

class Account {

    private $balance;

 

    public function __construct($initialBalance) {

        $this->balance = $initialBalance;

    }

 

    public function deposit($amount) {

        if ($amount < 0) {

            throw new InvalidArgumentException("Deposit amount cannot be negative.");

        }

        $this->balance += $amount;

    }

 

    public function getBalance() {

        return $this->balance;

    }

}

 

// Using the Account class with error handling

try {

    $account = new Account(100);

    $account->deposit(50);

    echo "Balance: $" . $account->getBalance(); // Output: Balance: $150

 

    $account->deposit(-20); // This will throw an exception

} catch (InvalidArgumentException $e) {

    echo "Error: " . $e->getMessage(); // Output: Error: Deposit amount cannot be negative.

}

Explanation:

  • The Account class encapsulates balance management and includes a method deposit that checks for negative amounts, throwing an InvalidArgumentException when this condition is met.
  • The usage of a try-catch block allows graceful error handling, providing feedback to the user instead of crashing the program.

These additional assignments further reinforce the understanding of Object-Oriented Programming concepts, such as inheritance, abstract classes, interfaces, composition, static properties, and error handling in PHP. Encourage students to experiment with the code and modify it to deepen their comprehension.


Post a Comment

0Comments

Post a Comment (0)