Mastering HTTP Response Status : A Journey from Beginner to Expert
Read More
OOPs Interview Questions
Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.
Advantages of OOPs
There are various advantages of object-oriented programming.
· OOPs provide reusability to the code and extend the use of existing classes.
· In OOPs, it is easy to maintain code as there are classes and objects, which helps in making it easy to maintain rather than restructuring.
· It also helps in data hiding, keeping the data and information safe from leaking or getting exposed.
· Object-oriented programming is easy to implement.
·Inheritance - a way of creating new classes from existing class without modifying it.
·Encapsulation - a way of hiding some of the private details of a class from other objects.
·Polymorphism - a way of using common operation in different ways for different data input.
Object-oriented programming is based on the following principles:
Abstraction helps in the data-hiding process. It helps in displaying the essential features without showing the details or the functionality to the user. It avoids unnecessary information or irrelevant details and shows only that specific part that the user wants to see.
Or
Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. Consider a real-life example of a man driving a car. The man only knows that pressing the accelerator will increase the speed of the car or applying brakes will stop the car but he does not know how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of an accelerator, brakes, etc. in the car. This is what abstraction is.
The benefits of Abstraction includes:
Simplified Interface: Abstraction allows hiding complex implementation details and exposing a simplified interface to the user.
Code Maintenance: By focusing on essential features and hiding unnecessary implementation details, abstraction improves code maintainability.
Flexibility: Abstraction enables the creation of generalized interfaces, which can be implemented differently for various use cases.
The wrapping up of data and functions together in a single unit is known as encapsulation. It can be achieved by making the data members' scope private and the member function’s scope public to access these data members. Encapsulation makes the data non-accessible to the outside world.
Encapsulation is about keeping data safe within a class. It restricts access to some parts of the class so that the data cannot be changed accidentally or in the wrong way.
The benfits of encapsulation include:
Data Protection: Encapsulation hides the internal implementation details of an object, protecting the data from unauthorized access or modification.
Code Organization: Encapsulation helps organize code by grouping related data and functions together within a class.
Code Reusability: Encapsulation facilitates code reusability by encapsulating functionality within objects.
<?php
class BankAccount {
private $balance; // Hidden balance property
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
// Method to check the balance
public function getBalance() {
return $this->balance;
}
// Method to add money, with a check
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
}
$account = new BankAccount(100); // New account with $100 balance
echo $account->getBalance(); // Shows balance: 100
$account->deposit(50); // Adds $50 safely
echo $account->getBalance(); // Shows updated balance: 150
?>
Inheritance allows one class to inherit properties and methods from another, promoting reusability and reducing redundancy.
Or
Inheritance allows one class to "inherit" or receive properties and methods from another class. This is like a child inheriting traits from a parent. Inheritance helps you to avoid repeating code and creates a clear relationship between classes, making it easy to share and reuse functionality.
The benefits of Inheritance include:
Code Reusability: Inheritance allows classes to inherit properties and behavior from a base class, promoting code reuse.
Hierarchical Organization: Inheritance establishes a hierarchical relationship among classes.
Polymorphism: Inheritance enables polymorphism, where objects of derived classes can be treated as objects of their base class.
<?php
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function sound() {
return "Some generic sound";
}
}
class Dog extends Animal {
public function sound() {
return "Woof!";
}
}
class Cat extends Animal {
public function sound() {
return "Meow!";
}
}
$dog = new Dog("Buddy");
$cat = new Cat("Whiskers");
echo $dog->sound(); // Output: Woof!
echo $cat->sound(); // Output: Meow!
?>
Explanation
Inheritance helps us organize code better and reuse common functionality without rewriting it, making it easier to maintain and extend.
Polymorphism means "many forms." It allows one function or method to work in different ways depending on the object”. This makes it easy to use the same operation on different types of objects.
In simpler terms, polymorphism lets you use a single method to perform different actions, depending on the type of object that calls it. This is especially helpful when you have different classes that are related but behave differently.
<?php
class Dog {
public function sound() {
return "Woof!";
}
}
class Cat {
public function sound() {
return "Meow!";
}
}
class Bird {
public function sound() {
return "Chirp!";
}
}
function animalSound ($animal) {
echo $animal->sound()
}
$dog = new Dog();
$cat = new Cat();
$bird = new Bird();
animalSound ($dog); // Output: Woof!
animalSound ($cat); // Output: Meow!
animalSound ($bird); // Output: Chirp!
?>
In this example:
That’s the power of polymorphism!
Class
A class is like a blueprint or a template for creating objects. It defines the properties (data) and behaviors (functions or methods) that all objects created from the class will have.
A class typically includes:
1. Properties (also called attributes): These are the data or characteristics of the objects.
2. Methods: These are actions or behaviors that the objects can perform.
An object is a specific instance of a class. It has real data and can perform actions defined by the class.
<?php
class Car {
// attributes or Properties
public $color;
public $brand;
// methods
public function drive() {
return "The car is driving.";
}
}
?>
Example for Clarity
Imagine you have a Car
class. This class would describe:
color
, brand
, and model
.drive()
and stop()
.But the Car
class itself isn’t a real car—it’s just the blueprint.
<?php
$car1 = new Car(); // Creating an object of Car class
$car1->color = "Red"; // Setting properties for this object
$car1->brand = "Toyota";
$car2 = new Car(); // Creating another object of Car class
$car2->color = "Blue";
$car2->brand = "Honda";
echo $car1->drive(); // Output: The car is driving.
?>
In this example:
Summary
Overriding in PHP is same as other programming languages, but overloading is quite different.
We already know that when we inherit a child class from a parent class, the child class has access to the methods of its parent class. Let’s say we have an Animal class with a method move(). The following code is the implementation of this class.
class Animal{
public function move(){
echo "The animal is moving.";
}
}
Now, we want to make the Cat class a child of Animal class. The cat class will inherit the move method as well. Now the problem is, the move method of cat is so generic that it is saying “The animal is moving”, we want to make a specialized version of move method for the Cat class only, which will tell that “The cat is moving” instead of “The animal is moving”. So, to make the specialized version out of a generalized version, we override the move method in the child class.
The overridden method will have the same header as its parent method, but it has its own implementation. The following code is the implementation of the Cat class along with the overridden move method.
class Cat extends Animal{
public function move(){
echo "The cat is moving.";
}
}
To make use of the overridden move method, let’s create an object of the Cat class and call its move method.
$cat = new Cat();
$cat->move();
The above lines of code will produce the output “The cat is moving”.
Method Overloading:
Method overloading is all about having two or more methods with the same name but with a different number of parameters. Let’s understand this concept with an example.
Suppose we have a class Calculator with a method named add, which accepts two parameters and return the sum of them. See the following code:
class Calculator{
public function add($a, $b){
return $a + $b;
}
}
The method written above will only add two parameters. What if we want to add three numbers together? Obviously, we can create another method and call it “addThree”, but this will confuse the user as the user have to call different methods with different names but the purpose of these methods is the same. To avoid this, PHP, like many other languages, allows us to write the methods with the same name with the distinction in the number of parameters to make them unique.
The following lines of code will have two methods with the same name but with the different number of parameters:
class Calculator{
public function add($a, $b){
return $a + $b;
}
public function add($a, $b, $c){
return $a + $b + $c;
}
}
To call the methods:
$obj = new Calculator();
echo $obj->add(2, 3);
echo $obj->add(2, 3, 4);
The second and third line of the above code will display 5 and 9, respectively.
Please note that the method overloading is only available in the class methods and not in non-class functions.
The simple difference between method overriding and method overloading:
Method Overriding: Same name, the same number of parameters, different body.
Method Overloading: Same name, different number of parameters, and a different body
Benefits of OOP include the following:
· Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier.
· Reusability. Code can be reused through inheritance, meaning a team does not have to write the same code multiple times.
· Productivity. Programmers can construct new programs quickly through the use of multiple libraries and reusable code.
· Easily upgradable and scalable. Programmers can implement system functionalities independently.
· Interface descriptions. Descriptions of external systems are simple, due to message-passing techniques that are used for object communication.
· Security. Using encapsulation and abstraction, complex code is hidden, software maintenance is easier and internet protocols are protected.
· Flexibility. Polymorphism enables a single function to adapt to the class it is placed in. Different objects can also pass through the same interface.
· Code maintenance. Parts of a system can be updated and maintained without needing to make significant adjustments.
· Lower cost. Other benefits, such as its maintenance and reusability, reduce development costs.
The structure, or building blocks, of object-oriented programming include the following:
· Classes are user-defined data types that act as the blueprint for individual objects, attributes and methods.
· Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined.
· Methods are functions that objects can perform. They are defined inside a class that describe the behaviors of an object. Each method contained in class definitions starts with a reference to an instance object. Additionally, the subroutines contained in an object are called instance methods. Programmers use methods for reusability or keeping functionality encapsulated inside one object at a time.
· Attributes represent the state of an object. In other words, they are the characteristics that distinguish classes. Objects have data stored in the attributes field. Class attributes belong to the class itself and are defined in the class template.
· Association. This is the connection between one or more classes. Associations can be one to one, many to many, one to many or many to one.
Recent posts form our Blog
0 Comments
Like 1