If knowledge is power, then sharing knowledge is ultimate powertrip
Latest Updates
You are here: Home >> PHP >> OOPS interview qestions in PHP

OOPS interview qestions in PHP

There are few OOPS based questions that are frequently asked in interviews. So, here are few OOPS interview questions in PHP.

Abstraction vs. Encapsulation

encapsulation is wrapping up of a data into single unit and abstraction is hiding unnecessary background  details and representing only important and essential detail

Encapsulation protects abstractions. Encapsulation is the bodyguard; abstraction is the VIP.
Encapsulation provides the explicit boundary between an object’s abstract interface (its abstraction) and its internal implementation details. Encapsulation puts the implementation details “in a capsule.” Encapsulation tells users which features are stable, permanent services of the object and which features are implementation details that are subject to change without notice.
Encapsulation helps the developers of an abstraction: it provides the freedom to implement the abstraction in any way consistent with the interface. (Encapsulation tells developers exactly what users can and cannot access.) Encapsulation also helps the users of an abstraction: it provides protection by preventing dependence on volatile implementation details.
Abstraction provides business value; encapsulation “protects” these abstractions. If a developer provides a good abstraction, users won’t be tempted to peek at the object’s internal mechanisms. Encapsulation is simply a safety feature.

Encapsulation is defined as the process of wrapping up the data members and member functions together into a single unit.It is dependent on the object data type.
Abstraction is the process of eliminating unnecessary details thereby highlighting the important features.It is independent of the object data type.

A real world example, consider u have setup a big building(say a company), the details regarding materials used to built (glass, bricks), type of work, manager of the company, number of floors, design of the building, cost of the building etc. can be classified as ABSTRACTION. Whereas, type of glass or bricks(grey one or red one) used, who all work for which all departments n how they work, cost of each and every element in the building etc. comes under Data ENCAPSULATION.

What is the difference between inheritance and polymorphism?


This can be a confusing topic because one can argue that sharing method attributes between a super or abstract class with a derived class could be described by either Polymorphism or Inheritance. One significant difference could be illustrated as to when or under what circumstances you would you use one or the other.

An ideal instance of using Inheritance would be when you want to create an entirely new class, but wish to borrow a group of existing attributes or methods resident in an existing Abstract or super Class, instead of re-inventing the wheel. If you had an Abstract Class Carnivore and wanted to create a subclass Cat, you could instantly inherit all the methods that were common in Carnivore that applied to Cat without writing new code.

Polymorphism could be best applied when you had an existing SubClass that you wanted to modify or add a feature that could borrow a method that existed in a higher class. Take the Cat subclass, which inherited attributes from Carnivore, and you wanted to add the method Stalk, which would generically describe how a carnivore approaches its prey. However its implementation in Cat would detail the stealth it uses that are unique to a Cat.

Difference between function overloading and polymorphism

Polymorphism is simply the ability to have many different methods (Or functions, for those who are used to C-Type programs) to have the same name, but act differently depending on the type of parameters that were passed to the function.

So for example, we may have a method called punch, which accepts no parameters at all, and returns an integer:

public int punch()
{
return 3;
}

We could also have a method named punch that accepts a String and returns a boolean.

public boolean punch(String poorGuyGettingPunched)
{
if(poorGuyGettingPunched.equals(“joe”))
{
System.out.println(“sorry Joe”);
return true;
}
else
return false;
}

That is called polymorphism… And strangely enough, it is also called overloading.

Do not confuse this with overriding, which replaces a function or method with a new one, or rather, hides the old method and replaces it with a new one.

Typically when you overload something (a function for example), you’re giving a new option as to how the client/programmer can use that function.

Polymorphism is slightly more difficult to describe. It’s as if you’re giving new meaning to an existing procedure in a way that is transparent to the client.

Difference between method overriding and overloading

Method overriding is a feature in Object Oriented programming language. This is used to implement a method for subclass which overrides in other words replaces the implementation of the super class. Overloading the concept of providing different meaning to a object based on the context of its presence. Overloading is one type of polymorphism and this is also a feature in Object Oriented programming language.

Difference between abstract class and interface

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let’s explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Can We Override the Private function of the Base class in the derived class?

The private function does not get inherited to the derived class..

it is impossible to override a private method of a baseclass.

Public method –> Overridden in all classes
Protected –> these methods can be overrided in the class inheriting it.

When to use an Abstract Class and an Interface

Abstract Class vs an Interface.

I normally used this “What is the difference between an Abstract Class and an Interface” as a quick way to gauge someone. Lots of times, its the first or second question I will ask. I cannot tell you how many times people will mess this question up. 9 times out of 10, people read about it at some www.basicinterviewquestions.com (not a real site hehe), giving the canned response of “You can define default functionality in an abstract class and you can just define functions in an interface”. The curve ball is thrown when you ask “Why would you use one over the other?”. That will earn you the ‘deer in headlights’ look. The other 1 out of 10 you will get a “I never had to use that so I don’t know”.

At the top level, the are a few basic difference. Abstract classes allow for default default function definition. This means that whatever class extends the abstract class will have access to this. If we have a base class where all the classes will perform the same function, then we can define that in our Abstract class. An interface is a list of functions or properties that if a class implements it, it will have to have those functions defined within it. It is a situation of “Is-A” vs “Can-Do-this”. Objects that extends an Abstract class “Is-A” base class. Objects that implement “Can-Do-This”. Now if I asked this question and got the answer, yes, that would be the correct answer. However, I want to know why one would want to use an interface over an abstract class, and vice versa.

When to prefer an interface

Lets say you have an interface for a Director and another interface for a Actor.

public interface Actor{

Performance say(Line l);

}

public interface Director{

Movie direct(boolean goodmovie);

}

In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes, we can implement both Actor and Director. We could even define an ActorDirector interface that extends both like this:

public interface ActorDirector extends Actor, Director{

}

We could achieve the same thing using abstract classes. Unfortunately the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities.

When to prefer an Abstract class

Abstract classes allow you to provide default functionality for the subclasses. Common knowledge at this point. Why is this extremely important though? If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class. Why? Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if its just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.

Speaking from personal experiences, frameworks is a good place to show when and where to use both an abstract class and an interface. Another general rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class. An example of this would be something like a business rules engine. This engine would take in multiple BusinessRules as classes perhaps? Each one of these classes will have an analyze function on it.

public interface BusinessRule{

Boolean analyze(Object o);

}

This can be used ANYWHERE. It can be used to verify the state of your application. Verify data is correct. Verify that the user is logged in. Each one of these classes just needs to implement the analyze function, which will be different for each rule.

Where as if we were creating a generic List object, the use of abstract classes would be better. Every single List object is going to display the data in a list in some form or another. The base functionality would be to have it go through its data provider and build that list. If we want to change that List object, we just extend it, override our build list function, change what we want and call super.buildList();

Almost everyone knows that interfaces means you are just defining a list of functions and that abstract classes has the option of providing default functionality. The snags come when you drop the ‘why would I use one over the other?’. Abstract classes and interfaces are some of the most important fundamentals of object oriented programming. Just knowing the differences between the two is not enough. When you can look at a situation and make a strong recommendation, you will known you have a much stronger knowledge of object oriented programming. Also it helps during interviews. .

Second answer

I think concrete classes can do whatever an abstract class can do. But just for the sake of cleaner and clearer design, one of the pros of OOP, we use abstract classes or interfaces.

For example: If you have a super class Figure which is used to calculate area of a figure like a rectangle, square, triangle or any other polygon. This figure SHOULD require dimensions to be passed to it to calculate area. But area formula differs based on the type of polygon. So it is better to calculate area in respective sub classes instead of defining it here as say area = NULL.

Now if subclasses say Triangle and Rectangle wants to use the super class. We have two scenarios:

1. Using concrete class: Here you can define some body or no body in the area() method. But if you don’t define area at all in the super class then all subclasses might define it the way they like like area1() or triangleArea() or areaRect(). Some folks might not even define the area because they don’t that the purpose of that super class is to calculate area and not forming a polygon object by passing dimensions as arguments in the constructor(let us say). This makes things a little messy.
2. Using abstract class: Here you don’t define the area method. But you enforce the subclasses to define the area method in the way it is defined in the super class.

This is just for cleaner and clearer design.

3. Using interfaces: This will have same kind of abstractness in the design but for some reasons(probably for IS-A vs CAN-DO differences) noted above we can choose whether to use interface at all or not.

 

About Jawed Shamshedi

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Scroll To Top