Scenario for Abstract Classes & Interfaces in Java
During java interviews a common question has been asked i.e.
Tell us the scenario where we should use Abstract class and where we should use an interface?
In this post I will explain this question in a easy to understand manner, so lets start.
Key Point about Abstract Class & Interface
Both of them are used for generalization & in java abstraction is achieved by both of these two.
“Abstract classes are used when behaviour of different objects are known & interface are used when behaviour of different objects are not known. Objects belongs to different classes.”
Here the term behaviour means methods definition in a class, but for some time just skip this definition.
Lets have a look on an example. Let’s consider three different classes Employee, BusinessMan, Singer. All of these are the categories of Person Abstract Class/ Interface. Lets consider these classes having common behaviour i.e. eat(), drink(), sleep(). i.e. method definition of these methods are same.
Note: method definition means inner logic of a method.
In this case as all of these classes have common behaviour so we can place there definition at one place to avoid code redundancy. This is the scenario where we should use a Abstract class & all sub classes of this Abstract class will get the common definition of these behaviors.
In terms of coding
Create a Abstract class Person having a definition for these methods eat(), drink(), sleep() as shown
abstract class Person{
void eat(){…}
void sleep(){…}
void dring(){…}
…
}
& now all sub-classes of this abstract class have common definition of these methods and may also have new methods.
ex.
class Singer extends Person{
…
}
same for all other classes.
Lets have a look on another scenario, consider three different classes Employee, BusinessMan, Singer. All of these are the categories of Person Abstract Class/ Interface.
All of these classes have a common behaviour income() but how they earn it, is different i.e. behaviour name is same but definition changes from person to person. So this is a scenario where we should use interface. By doing this we will have a common behaviour name but able to provide different definition.
If we use abstract class in this scenario then code redundancy will take place & it’s not a good coding practice.
In terms of coding, Let’s create a interface named as Person having only one method income().
interface Person{
void income();
}
class Employee implements Person{
@Override
income(){
…
}
}
same for all other classes.
Now I think the above explanation make sense to you & explain you where we should use Abstract class and where we should use Interfaces.
Happy Coding
Namah Shivay
Recent Comments