Object Oriented Programming (OOP)s Concepts
OOP Design Principles
An application that implements Object Oriented Programming (OOP) Concepts is distinguished by four design principles. The four design principles are encapsulation, abstraction, inheritance and polymorphism.
- Encapsulation
Encapsulation is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse.
In short, it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data. In Java, the basis of encapsulation is the class. A class defines the structure and behavior (data and code) that will be shared by a set of objects. Each object of a given class contains the structure and behavior defined by the class, as if it were stamped out of a mold in the shape of a class. A class is a logical construct, an object has physical reality.
When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the member variables.
Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity to the implementation inside the class. Each method or variable in a class may be marked public or private. The private methods and data can only be accessed by the code, which is a member of the class. The public method has all details essential for external users.
Encapsulation hides the inner workings of an object from outside users of the object. This protects outside users from making internal changes or optimizations to such objects. The object needs only to maintain its external functionality to support its clients. Internal details, such as data representation, should not be accessible externally.
- Abstraction
Abstract class is a class that cannot be instantiated but can be inherited only.It's a class with at least one abstract method must be Abstract class.
While inheriting from Abstract class, all abstract methods of parent class must be defined with same or less visibility by Child Class. E.g. if the abstract method is defined as protected, the function implementation must be defined as either protected or public but not private. Furthermore, the signatures of methods must match.
The principle of abstraction is modeling real world objects as objects in JAVA. However, these objects are only modeled at a certain level of detail. Only the behavior and data that is needed by your application will be included in your model.
The abstraction design principle focuses on the essential characteristics of an object. In OOP, abstraction defines the conceptual boundaries of an object. These boundaries distinguish one type of object from another.
- Inheritance
It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors.
The inheritance design principle allows a class to inherit the characteristics of another class. When inheritance is used in an application, the application consists of classes that are arranged in hierarchies. The classes defined at a the lower levels of a hierarchy inherit from the classes higher up in the hierarchy.
By creating a hierarchy of classes, the characteristics and code of a class are made reusable. A class can inherit characteristics from other classes and provide additional features. The new class has its own attributes and the attributes of existing class. This feature provides extensibility and reusability in classes.
- Polymorphism
It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation. In general Polymorphism means "one interface, multiple methods". This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (i.e. method) as it applies to each situation.
On the lighter side, extending this analogy to a dog, its sense of smell is polymorphic. If the dog smells a cat, it will bark and run around it. If the dog smells its food, it will salivate and run to its bowl. Note that the same sense of smell is at work in both the cases. The difference is what is being smelled, that is, the type of data being operated upon by the dog's nose.
Polymorphism refers to the ability of an object to take on different forms depending upon the situation. Consider an example of a class Sedan that inherits from the class Car that inherits from the class Vehicle. An instance of the Sedan class can be referred to as a Sedan, a Car or a Vehicle.
Polymorphism provides flexibility to an application based on requirements. It simplifies coding and reduces the rework involved in developing and modifying an application. This is because different types of objects can react to the same type of stimulus.
Class
Class is a collection of constants, methods and properties. Any non-reserved word can be a class name. Basic class definition starts with a reserved keyword “class” and then followed by the name of class finally followed by curly braces.
Properties
These are variables of class. These can be defined using keywords public, protected or private (scope operators) and then normal variable declarations. “var” is exceptional in php5 and if used, by default, it means public.
Non-Static properties are used using " -> " i.e. Object Operators whereas Static properties are used using "::" i.e. Scope Resolution operator.
Class Constants
Constants can be defined using the word " const " for a property. Constant differ from regular variables where you don't use " $ " for constants e.g. const abc = "pqr";
Here, value assigned to constant must be constant and could not be variable, a function call, a property or a mathematical operation for that matter.
It can be accessed as self::constant within a class or using semicolon and class name as MyClass::constant outside the class.
Constructors & Destructors
Constructor methods get called automatically on each newly creating object. In case of class extended, a parent class constructor needs explicit calls & does not gets called when child class object is created. It needs parent::__construct() call to evoke.
PHP5 gives backward compatibility where if class constructor is not found and if class is not inherited from another parent class then it tries to search for old-style constructor function, by the name of class.
Destructor methods will be called as soon as there are no other references to a particular object or during shutdown sequence or script execution is stopped using exit();
Like constructors, destructor method will be called as soon as there are no other references to a particular object or in any order during the shutdown sequence. Like constructors, a parent class destructor needs explicit call and does not get called automatically when child class object is freed. It needs parent::__destruct() call to evoke.
Visibility
Visibility of property or method can be defined using keywords public, protected or private.
- Public : can e accessed everywhere
- Protected: can be accessed only within the class itself & by inherited & parent class.
- Private: can be accessed only by class that defines it.
Scope Resolution Operator ( :: )
Double colon is a scope resolution operator that allows access to static, constant and overridden properties and methods of class.
Static Keyword
Declaring class methods and properties as Static makes them accessible without instantiation of class. Static property can not be accessed with class object but static method can. Static properties can not be accessed using " -> ".
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Object Interface
Interface defines the methods put does not implement it. Interface specifies which methods a class must implement without having to define those methods handling.
Interfaces are defined using "interface" keyword, but without having any of the methods having their contents defined. All methods declared in an interface must be public.
To implement interface, the "implements" operator is used. All methods in interface must be implemented within a class. Classes may implement more than one interfaces if desired by separating each with comma.
Object Clone
When one assigns an object from one variable to another using "=" operator, you do not copy it, but merely assign a handle or reference to it. However, situations will arise where one will actually want to assign a full copy of an existing object to a new variable. This is known as cloning, and is done via the "clone" operator.
When you clone an object in PHP, the language creates a new instance of a class and assigns copies of the corresponding variables in the original instance to this new object's member variables by default. However, this is a shallow copy, meaning that if one of those member variables is itself a reference to an object, only that reference is copied.
If the default behavior for cloning is not sufficient for your needs, you can implement the __clone function in your class, which PHP calls after it has performed the shallow copy of the member variables.
Difference between Abstract class and an Interface
Abstract classes can have implementations for some of its members (Methods), but the interface class can't have implementation for any of its members.
An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can't implement methods.
An abstract class can contain fields, constructors or destructors and implement properties. An interface can not contain fields, constructors or destructors and it has only the property's signature but no implementation.
An abstract class can not support multiple inheritances but an interface can support multiple inheritances. Thus a class may inherit several interfaces but only one abstract class.
A class implementing an interface has to implement all the methods of the interface but the same is not required in case of an abstract class.
Various access modifiers such as abstract, protected, internal, public, virtual etc. are useful in abstract classes but not in interfaces.
Abstract classes are faster than interfaces.
Class can inherit only one abstract class.
Class can implement more than one interface.
Using interface we can achieve multiple inheritance. We use interface where one class can not extend more than one class (in JAVA).
Difference between Polymorphism and Method Overloading
The difference between polymorphism and method overloading is in the time when the actual method to execute is determined. The reason for this is that when a method is overloaded, such as in :
account = new BankAccount();
account = new BankAccount(1000);
The compiler can tell which constructor to use by the method signature, including the number and types of parameters provided. This selection of a method to use at compile time, before the program ever runs is called early binding
On the other hand, when we use a polymorphic method call such as x.getMeasure() the actual getMeasure() method called depends on what type of object x refers to. Because objects are not constructed until the program runs, the method called is determined at run-time. Therefore, the virtual machine, not the compiler selects the appropriate method. This method selection is called late binding
The Best answer is that both overloading and overriding are different aspects of polymorphism.
static / early binding polymorphism: overloading
dynamic / late binding polymorphism: overriding
Magic Methods
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __isset(), __unset(), __sleep (), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You can not have functions with these names in any of your classes unless you want the magic functionality associated with them.
serialize() checks if your class has a function with the magic name __sleep (). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variable of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
The intended use of __sleep () is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstructs any resources that the object may have.
The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
- PHP 4
- PHP 5
- Both Option, PHP 4 & PHP 5
- Neither in PHP 4 nor in PHP 5
- Protected
- Private
- Public
- None of above
- int
- var
- private
- None of above
- Only methods
- Only data members
- Only constructors
- Both methods and data members
- True
- False
- PHP 4 and PHP 5
- PHP 5
- PHP 4
- Constructor of Class
- Magic Method
- Class Method
- All of above
- True
- False
class clsMessage {
private $strMessage;
function _construct() {
$this->strMessage = "This is default Message";
}
public function fnSetMessage($strMsg) {
if($strMsg!='')
$this->strMessage = $strMsg;
echo $this->strMessage;
}
}$objMsg = new clsMessage();
$objMsg->fnSetMessage('');
- It will print "This is default Message"
- It will give error
- It will print "" i.e. blank
- All above are false
- True
- False
- True
- False
- True
- False
- the constructor of class
- Sum of it's functions
- The name of the class
- None of above
- True
- False
- Encapsulation
- data mining
- Inheritance
- None of above
- Subordinate class
- Base class
- Child class
- None of above
- True
- False
- with no data members
- with no methods
- function prototypes with no bodies
- both 1 and 3
- Encapsulation
- Multiple Inheritance
- Function Prototyping
- All of above
- It lacks data members
- It lacks implementation
- There is no purpose if interface.
- All of the above
- Interface
- Encapsulation
- Security
- All of above
- Standard PHP Library
- Stored Procedural Language
- Secure PHP Lib
- Standard Package Library
- Make a code much cleaner
- Reduce amount of error-trapping
- Offer relief from un-inspiring tasks
- All of the above
- mysql intended
- mysql indexed
- mysql improved
- mysql implicit
- PHP Data Objects package
- PHP database objects
- Database compatible versioning
- None of the above
- True
- False
- instance variable
- data member
- properties
- All of above
- True
- False
- $this
- this
- No need, as they are global to class
- None of above
- PHP 4
- PHP 5
- Both PHP 4 and PHP 5
- This is invalid
Comments
Anonymous (not verified)
Wed, 11/22/2017 - 12:09
Fantastic, just what I needed
Fantastic, just what I needed.
Thanks a lot !!
Add new comment