Assignments on Class 20: Introduction to Object-Oriented Programming (OOP) - Part 2

Rashmi Mishra
0

Assignments on Class 20: Introduction to Object-Oriented Programming (OOP) - Part 2

Here are some assignments based on the concepts covered in "Introduction to Object-Oriented Programming (OOP) - Part 2," along with their solutions and explanations.


Assignment 1: Creating a Class with Properties and Methods

Task:

  1. Create a class called Student with the following properties:
    • name (public)
    • age (public)
    • studentId (private)
  2. Add the following methods:
    • getStudentDetails() (public) to return the name and age of the student.
    • setStudentId($id) (private) to set the student ID.
    • getStudentId() (public) to return the student ID.

Solution:

php

Copy code

class Student {

    public $name;

    public $age;

    private $studentId;

 

    // Method to get student details

    public function getStudentDetails() {

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

    }

 

    // Method to set student ID (private)

    private function setStudentId($id) {

        $this->studentId = $id;

    }

 

    // Method to get student ID

    public function getStudentId() {

        return $this->studentId;

    }

 

    // Public method to initialize student ID

    public function initializeStudentId($id) {

        $this->setStudentId($id);

    }

}

 

// Creating an object of the Student class

$student = new Student();

$student->name = "Alice";

$student->age = 21;

$student->initializeStudentId("S12345");

 

// Displaying student details

echo $student->getStudentDetails(); // Output: Name: Alice, Age: 21

echo ", Student ID: " . $student->getStudentId(); // Output: Student ID: S12345

Explanation:

  • Properties: name and age are public, so they can be accessed directly. studentId is private, so it cannot be accessed directly outside the class.
  • Methods:
    • getStudentDetails() returns the student's name and age.
    • setStudentId() is a private method used to set the student ID.
    • getStudentId() returns the private student ID.
    • initializeStudentId() is a public method that allows the student ID to be set indirectly.

Assignment 2: Understanding Access Modifiers

Task:

  1. Create a class called BankAccount with the following properties:
    • accountNumber (public)
    • accountBalance (protected)
    • accountHolderName (private)
  2. Add the following methods:
    • getAccountHolderName() (public) to return the account holder's name.
    • deposit($amount) (public) to add the amount to the account balance.
    • getAccountBalance() (protected) to return the account balance.

Solution:

php

Copy code

class BankAccount {

    public $accountNumber;

    protected $accountBalance;

    private $accountHolderName;

 

    // Method to get account holder name

    public function getAccountHolderName() {

        return $this->accountHolderName;

    }

 

    // Method to deposit amount

    public function deposit($amount) {

        $this->accountBalance += $amount;

    }

 

    // Protected method to get account balance

    protected function getAccountBalance() {

        return $this->accountBalance;

    }

 

    // Public method to initialize account holder name

    public function initializeAccountHolderName($name) {

        $this->accountHolderName = $name;

    }

}

 

// Creating an object of the BankAccount class

$account = new BankAccount();

$account->accountNumber = "BA98765";

$account->initializeAccountHolderName("Bob");

$account->deposit(500);

 

// Accessing account details

echo "Account Number: " . $account->accountNumber . "\n"; // Output: Account Number: BA98765

echo "Account Holder: " . $account->getAccountHolderName() . "\n"; // Output: Account Holder: Bob

 

// Cannot access accountBalance directly

// echo $account->accountBalance; // Error: Cannot access protected property BankAccount::$accountBalance

Explanation:

  • Properties: accountNumber is public and can be accessed directly. accountBalance is protected, so it can only be accessed within the class or by subclasses. accountHolderName is private, so it can only be accessed within the class.
  • Methods:
    • getAccountHolderName() returns the account holder's name.
    • deposit() adds the specified amount to the account balance.
    • getAccountBalance() is protected and cannot be accessed outside the class.

Assignment 3: Creating a Subclass

Task:

  1. Create a parent class called Animal with:
    • A protected property name.
    • A public method speak() that returns a string indicating the sound the animal makes.
  2. Create a subclass called Dog that extends Animal and:
    • Implements the speak() method to return "Woof!".

Solution:

php

Copy code

class Animal {

    protected $name;

 

    public function __construct($name) {

        $this->name = $name;

    }

 

    public function speak() {

        return "Some generic animal sound.";

    }

}

 

class Dog extends Animal {

    public function speak() {

        return "Woof!";

    }

}

 

// Creating an object of the Dog class

$dog = new Dog("Buddy");

echo "Dog Name: " . $dog->name . "\n"; // Output: Dog Name: Buddy (protected, so this won't work)

// Accessing the speak method

echo "Dog Sound: " . $dog->speak(); // Output: Dog Sound: Woof!

Explanation:

  • Inheritance: The Dog class inherits from the Animal class.
  • Protected Property: The name property in Animal is protected, so it cannot be accessed directly from the Dog instance.
  • Overriding Methods: The speak() method in the Dog class overrides the method in the Animal class.

Assignment 4: Access Control Verification

Task:

  1. Modify the BankAccount class from Assignment 2 to include a method withdraw($amount) that allows withdrawing money from the account. Ensure that the balance cannot go below zero.

Solution:

php

Copy code

class BankAccount {

    public $accountNumber;

    protected $accountBalance;

    private $accountHolderName;

 

    public function getAccountHolderName() {

        return $this->accountHolderName;

    }

 

    public function deposit($amount) {

        $this->accountBalance += $amount;

    }

 

    public function withdraw($amount) {

        if ($amount > $this->accountBalance) {

            return "Insufficient balance!";

        }

        $this->accountBalance -= $amount;

        return "Withdrawal successful. New balance: $" . $this->accountBalance;

    }

 

    protected function getAccountBalance() {

        return $this->accountBalance;

    }

 

    public function initializeAccountHolderName($name) {

        $this->accountHolderName = $name;

    }

}

 

// Creating an object of the BankAccount class

$account = new BankAccount();

$account->accountNumber = "BA98765";

$account->initializeAccountHolderName("Bob");

$account->deposit(500);

 

echo $account->withdraw(200); // Output: Withdrawal successful. New balance: $300

echo $account->withdraw(400); // Output: Insufficient balance!

Explanation:

  • New Method: The withdraw() method checks if the amount to withdraw is greater than the current balance. If it is, it returns an "Insufficient balance!" message; otherwise, it deducts the amount from the balance and returns the new balance.
  • This demonstrates access control since the balance is protected and cannot be accessed directly.

Conclusion

These assignments provide students with a practical understanding of class properties, methods, and access modifiers in OOP. By implementing these concepts, students can grasp how encapsulation and visibility control work in real-world applications. Encourage students to modify and extend these examples to reinforce their learning!

4o mini

You said:

give some more

ChatGPT said:

ChatGPT

Here are additional assignments with solutions and explanations on Object-Oriented Programming (OOP) concepts, focusing on class properties, methods, and access modifiers.


Assignment 5: Implementing a Library System

Task:

  1. Create a class called Book with the following properties:
    • title (public)
    • author (public)
    • isbn (private)
  2. Add the following methods:
    • getBookDetails() (public) to return the title and author of the book.
    • setIsbn($isbn) (private) to set the ISBN of the book.
    • getIsbn() (public) to return the ISBN of the book.
  3. Create an object of the Book class and demonstrate the functionality.

Solution:

php

Copy code

class Book {

    public $title;

    public $author;

    private $isbn;

 

    // Method to get book details

    public function getBookDetails() {

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

    }

 

    // Method to set ISBN (private)

    private function setIsbn($isbn) {

        $this->isbn = $isbn;

    }

 

    // Method to get ISBN

    public function getIsbn() {

        return $this->isbn;

    }

 

    // Public method to initialize ISBN

    public function initializeIsbn($isbn) {

        $this->setIsbn($isbn);

    }

}

 

// Creating an object of the Book class

$book = new Book();

$book->title = "The Great Gatsby";

$book->author = "F. Scott Fitzgerald";

$book->initializeIsbn("9780743273565");

 

// Displaying book details

echo $book->getBookDetails(); // Output: Title: The Great Gatsby, Author: F. Scott Fitzgerald

echo ", ISBN: " . $book->getIsbn(); // Output: ISBN: 9780743273565

Explanation:

  • Properties: title and author are public, allowing direct access. The isbn property is private, accessible only through methods.
  • Methods:
    • getBookDetails() provides public access to book information.
    • setIsbn() is a private method for setting the ISBN, and getIsbn() is a public method to retrieve it.

Assignment 6: Creating a Simple Calculator

Task:

  1. Create a class called Calculator with the following properties:
    • result (protected)
  2. Add the following methods:
    • add($num1, $num2) (public) to add two numbers.
    • subtract($num1, $num2) (public) to subtract two numbers.
    • getResult() (protected) to return the current result.
  3. Demonstrate the usage of the Calculator class.

Solution:

php

Copy code

class Calculator {

    protected $result;

 

    // Method to add two numbers

    public function add($num1, $num2) {

        $this->result = $num1 + $num2;

        return $this->result;

    }

 

    // Method to subtract two numbers

    public function subtract($num1, $num2) {

        $this->result = $num1 - $num2;

        return $this->result;

    }

 

    // Protected method to get result

    protected function getResult() {

        return $this->result;

    }

}

 

// Creating an object of the Calculator class

$calculator = new Calculator();

echo "Addition: " . $calculator->add(10, 5) . "\n"; // Output: Addition: 15

echo "Subtraction: " . $calculator->subtract(10, 5) . "\n"; // Output: Subtraction: 5

Explanation:

  • Properties: result is protected and can only be accessed within the class and by derived classes.
  • Methods:
    • add() and subtract() are public methods to perform arithmetic operations and store the result.
    • The getResult() method is protected, meaning it cannot be accessed directly outside the class.

Assignment 7: Inheritance and Method Overriding

Task:

  1. Create a base class called Vehicle with the following properties:
    • make (public)
    • model (public)
    • year (protected)
  2. Add a method getVehicleInfo() (public) to return the vehicle's information.
  3. Create a subclass called Car that extends Vehicle and overrides getVehicleInfo() to include the number of doors (public).

Solution:

php

Copy code

class Vehicle {

    public $make;

    public $model;

    protected $year;

 

    public function __construct($make, $model, $year) {

        $this->make = $make;

        $this->model = $model;

        $this->year = $year;

    }

 

    // Method to get vehicle information

    public function getVehicleInfo() {

        return "Make: $this->make, Model: $this->model, Year: $this->year";

    }

}

 

class Car extends Vehicle {

    public $doors;

 

    public function __construct($make, $model, $year, $doors) {

        parent::__construct($make, $model, $year);

        $this->doors = $doors;

    }

 

    // Overriding method to get vehicle information

    public function getVehicleInfo() {

        return parent::getVehicleInfo() . ", Doors: $this->doors";

    }

}

 

// Creating an object of the Car class

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

echo $car->getVehicleInfo(); // Output: Make: Toyota, Model: Camry, Year: 2021, Doors: 4

Explanation:

  • Inheritance: The Car class inherits from the Vehicle class.
  • Method Overriding: The getVehicleInfo() method in Car overrides the method in Vehicle, adding more information (number of doors) while still calling the parent method to maintain base functionality.

Assignment 8: Implementing a Shopping Cart

Task:

  1. Create a class called Product with the following properties:
    • name (public)
    • price (public)
  2. Create a class called ShoppingCart with:
    • A private array products to store products.
    • A public method addProduct(Product $product) to add a product to the cart.
    • A public method getTotal() to calculate the total price of the products in the cart.

Solution:

php

Copy code

class Product {

    public $name;

    public $price;

 

    public function __construct($name, $price) {

        $this->name = $name;

        $this->price = $price;

    }

}

 

class ShoppingCart {

    private $products = [];

 

    // Method to add product to cart

    public function addProduct(Product $product) {

        $this->products[] = $product;

    }

 

    // Method to calculate total price

    public function getTotal() {

        $total = 0;

        foreach ($this->products as $product) {

            $total += $product->price;

        }

        return $total;

    }

}

 

// Creating product objects

$product1 = new Product("Laptop", 1000);

$product2 = new Product("Mouse", 25);

 

// Creating shopping cart object

$cart = new ShoppingCart();

$cart->addProduct($product1);

$cart->addProduct($product2);

 

// Displaying total price

echo "Total Price: $" . $cart->getTotal(); // Output: Total Price: $1025

Explanation:

  • Classes: The Product class represents individual items, while ShoppingCart manages a collection of products.
  • Access Modifiers: The products array is private, preventing external modification directly. Methods provide controlled access to add products and calculate the total price.

Assignment 9: Encapsulation and Data Hiding

Task:

  1. Create a class called Employee with the following properties:
    • name (public)
    • salary (private)
  2. Add methods:
    • setSalary($salary) (public) to set the salary.
    • getSalary() (public) to return the salary.
  3. Demonstrate encapsulation by attempting to access the salary directly.

Solution:

php

Copy code

class Employee {

    public $name;

    private $salary;

 

    // Method to set salary

    public function setSalary($salary) {

        $this->salary = $salary;

    }

 

    // Method to get salary

    public function getSalary() {

        return $this->salary;

    }

}

 

// Creating an object of the Employee class

$employee = new Employee();

$employee->name = "John Doe";

$employee->setSalary(50000);

 

// Displaying employee details

echo "Employee Name: " . $employee->name . "\n"; // Output: Employee Name: John Doe

// echo $employee->salary; // Error: Cannot access private property Employee::$salary

echo ", Salary: $" . $employee->getSalary(); // Output: Salary: $50000

Explanation:

  • Encapsulation: The salary property is private, preventing direct access from outside the class. The setSalary() and getSalary() methods provide controlled access.
  • Data Hiding: Attempting to access salary directly results in an error, demonstrating the principle of data hiding in OOP.

These assignments cover various aspects of OOP, including class creation, properties, methods, access modifiers, inheritance, and encapsulation. Let me know if you need further explanations or additional topics!


Post a Comment

0Comments

Post a Comment (0)