“Tell me about Abstract class and Interface” – most of the times my interviews started with this renowned question and I know many of you likewise confronted it many times. I had memorized the definitions and differences like a parrot but really didn’t knew what they were and how different they were then. So what they are and how they are implemented in programming, lets dive deep.
Abstract class and Interface can be termed as Steel and Mortar for building a software architecture and act as a base for building many complex softwares application.
Abstract class and Interface are the two very integral part of Object oriented programming concept – Abstraction.
Let us first understand what Abstraction is. The dictionary says that Abstraction is a quality of dealing with ideas rather than events; and this is what similarly implemented in the software engineering.
John Vogel Guttag, an American computer scientist, professor, and former head of the department of Electrical Engineering and Computer Science at MIT said-
The essence of abstraction is preserving information which is relevant in a given context and forgetting information which is irrelevant in that context.
What he says here, by employing abstraction in programming we can hide the implementation details and show only the necessary functionality to the user.
We have so many examples for abstraction in the real world; for instance a Laptop. There are various circuitry in the laptop but that is not visible to us, what’s visible to us is the interface that are screen, keyboard, touch-pad, buttons etc.
We don’t care about the internal processing we only care about what is visible to us, we don’t want to know about the details and this is simply Abstraction.
Abstraction can be implemented in using an Abstract class and Interface. We will understand this concept one by one.
A class is said to be an abstract class if it has Abstract keyword in it. I’m just kidding about it. I used to crack these types of answers in the class tests when I went unprepared.
But not exactly the above sentence is wrong we do have an abstract keyword in abstract class which simply denotes that our class is Abstract class.
The fundamental definition of Abstract class is that it can’t be instantiated i.e. we cannot create an object of an abstract class, it can only be inherited. Abstract class is merely said to be incomplete because the author of the class marked it as abstract and it awaits other user to be implemented.
For instance think of a car, say a Company Uno has created the skeleton or chassis of the car. This skeleton is build such a way that the car’s height and length can be altered by another company.
Now Company Dos buys this skeletons to build their all new car with their engine, gears, seats, windshields, headlights, logo etc. Company Dos has an option to some modification with height and length as the provision was provided by Company Uno.
Here Company Dos doesn’t know about how the chassis was built neither it knows how many screws and bolts were used; it knows only about the information which is necessary for it to build it’s car hence adopting Abstraction.
Abstract classes are similar to other base classes except for their instantiation and abstract methods. There can be more than one abstract methods in an Abstract class.
Abstract methods are basically the signatures of functions and they lack implementation. The foremost significance of using an abstract method is of providing a common base and definition for the inheriting classes as these methods act as a contract that must be implemented in the inheriting class.
Abstract class do have some similarities with base class:
- Abstract class do have constructors, but as they must be marked as protected (Since abstract classes can’t be instantiated, there’s no point in their having public or internal . If there is basic initialization logic that should run when an extending class instance is created, you can by all means put it in a constructor, but make that constructor private or protected).
- They can inherit other Classes and multiple Interfaces.
- They can have static methods and properties
Some important facts:
- Abstract class cannot be sealed
- There cannot be any private abstract class
- It is not necessary for abstract method to have abstract methods
- Cannot be instantiated
Why use them?
Abstract class are basically used to provide common functionalities and operations to the inheriting classes. It is like defining a prototype which the child classes can utilize later.
Abstract classes can be used to share code among several closely related classes. What closely related classes here means is when we have “Is-A” relationship among classes like Apple is a Fruit, orange is a fruit. Fruit can be an abstract class with common implementation like color, taste, type etc.
It totally depends on how you are creating your architecture, if you think that the instantiation of a class won’t be necessary then it’s better to create it as Abstract class.
Now enough of Abstract class now let us see about Interface:
What exactly is interface in real world?
– Interface can be said as a connection between two pieces of electronic equipment, or between a person and a computer.
What we can take from the above definition is that anything which act as a mediator between the two entities which helps to carry out communication is a kind of interface. Graphical user interface is such a relevant example to it.
Interface is similarly handled in the software engineering too. It is the blueprint of the class or can be understood as a contract that every inheriting class must follow.
Interface like Abstract class also provide Abstraction.
Remember the car example above?
Let say, Company Uno has created the skeleton of a car but has restricted any alteration in the dimension of the skeleton; which means Company Dos must strictly follow the contract specified by the fist company.
This is the same way Interface works. If child classes are inheriting from an Interface or multiple interfaces then they must implement all of the interface members.
Implementing an interface simply requires implementing all of its properties and methods, in whatever way is best for your class.
Some facts about Interface:
- Interface provide multiple inheritance.
- Interface have method definitions but no method implementation.
- They don’t have fields but can declare a property.
- By default interface members are public and virtual.
- You cannot specify any access specifier for the signature of interface members.
- Delegate cannot be declared in the interface.
- A class can inherit multiple interfaces also interface can inherit multiple interfaces.
Interface can be implemented explicitly using Interface name:
In Explicit interface implementation members are privately implemented whereas for Implicit implementation members are publicly implemented.
Why to use Interface?
- Interface are used in building of loosely coupled applications.
Let’s have a quick look on Coupling; coupling basically means the degree of information that two component share. Higher the degree of knowledge that one component has of another, higher is the degree to which the components are tightly coupled. An example will try to settle the complication.
I came across one real life example on online forum which says think of your body and skin as two component. Let body be the dependent component which is dependent on skin. The skin is attached tightly to your body but now I don’t like the color of my skin. Just imagine how painful it would be to remove your skin, change it color and attach again. Now think of a shirt, I like many colors and with the help of shirt I can cover my body with many different color of shirts. Shirt here is kind of interface. I know it is kind of irrational example but how easily it tries to explains abstraction.
Still not satisfied? Alright let us jump to programming boat then.
Suppose we have a Dependent Class called Car and also we have a Concrete classes BMW, Mercedes and Ferrari. All these concrete class have some similar operations and attributes like move, start, stop, etc. When the things are tightly coupled our Dependent class will contain pointer directly to the Concrete classes as shown below.
The code below shows our classes. There are 3 concrete classes BMW, Mercedes and Ferrari. All these classes consists of same operation but they may have different implementations. The class car is dependent car and wants to implement the operation from the mentioned dependent classes.
The fourth class example shows our dependent class Car which is implementing Move methods from the concrete classes 1st, 2nd and 3rd. Similarly, other methods will also implemented.
Now, below code shows how the Car class will be implemented in Program class
We can see how open code we have i.e. Car has all direct knowledge of all the classes even if we only need material about any single class.
Now comes the major twist; what if tomorrow I need to add a new car brand, then what?
Then we will have to modify the Car class again, add a new Brand and its operations. How stressful it appears. Also look at our code, how tedious, untidy and complicated it looks. It leaves no space for extensibility and no scope for systematic future enhancement.
How can I clean this up? We can use Interface. Let us see how.
We will create an Interface ICar and make concrete classes implement this interface.
By using interface the dependent class will now point to interface instead of Concrete classes. This interface ICar will act as a contract that all concrete must implement. So any class implementing the interface ICar must satisfy the dependency of dependent class Car without changing the it’s structure.
The above code shows our interface ICar which have method signatures. This methods must be implemented in the classes inheriting ICar. The class Bmw inherits ICar and implements all the method as shown in above code.
Now let us see how class Car will be using interface ICar.
In the above code we are creating a private reference variable _car of interface ICar. So instead of calling multiple methods for different concrete classes we will create method which are defined by the interface ICar.
For each method we are having ICar parameter which will be set to private reference variable _car and by using this variable we will make a call to methods i.e Move(), Start() and Stop(). Now our class Car looks organized and well-structured. So even if some other class is added which implements ICar, there will be no change required in Car class and our code becomes extensible.
The code below shows our Main method for the implementation of Car class.
We can also further cleanse our code by applying DIP (Dependency inversion principle) by implementing dependency injection to our code and using any of the IoC (Inversion of control) container. We will have a look at it later.
- Interfaces allows objects to interact easily
- Facilitate reuse of the software.
- Interface provide abstraction in coding, so they hide the implementation details.
- One of the most important features of Interface is that they provide multiple inheritance in programming languages like Java, C# and VB.
When to use Abstract class and when to use Interface?
Their implementation is totally based on system requirement.
If the requirement is of the abstraction which has some common methods, fields and properties; and who can also provide provision to have implementation of the depending class then I will use abstract class.
Abstract classes are incomplete implementation, so this provides partial implementation. If we wish to create multiple version of our component, then we can use Abstract class; this edges Abstract class over interface.
If the requirement is of defining a contract which must be implemented by all the implementing classes to implement their own operations, then the swift way is of using an Interface.
Multiple implementations can be implemented in inheriting class by multiple interfaces as interface delivers multiple inheritance.
Multiple inheritance proves to major advantage of interface over abstract and non-abstract classes but as I said it all about your necessity and nature of the application you are building.
Finally, below are some Differentiation between Abstract classes and Interfaces which you people can utilize in your interviews after explaining the long saga mentioned above.
|Methods||They have abstract and non-abstract methods, virtual methods, static and non-static methods.||They only have method signatures and Properties.|
|Fields and Properties||Static and non-static fields and properties.||Only properties are permitted not fields.|
|Inheritance||Supports single inheritance, can inherit classes and multiple interfaces.||Can inherit multiple interfaces.|
|Multiple Inheritance||No multiple inheritance.||Delivers multiple inheritance|
|Access modifiers||Can provide access modifiers for fields, properties and methods.||Cannot have access modifiers, by default all members are public.|
|Instantiation||We cannot create an object of abstract class but it can be used to create a reference variable of inheriting class.
Eg. absCar objbmw = new Bmw();
|Interface cannot be instantiated but it can be used to create a reference variable of inheriting class.
Eg. ICar objbmw = new Bmw();
|Constructor||Abstract class can have protected constructor.||Interface don’t have constructor.|
Well, that seems to be enough and I know that I’ve bored you to death but look at the positive side people we finally understand how abstraction works and how important are Abstract class and interface in Object oriented programming.
Hope this helps! If you have any issues, suggestions, feedback or concerns do comment below.