May 13, 2020
Estimated Post Reading Time ~

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 an easy to understand manner, so let's 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 the behaviour of different objects is known & interface is used when the behaviour of different objects is not known. Objects belong to different classes.”

Here the term behavior means methods definition in a class, but for some time just skip this definition.

Let's have a look at 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 is the same.

Note: method definition means the inner logic of a method.

In this case, all of these classes have common behavior so we can place there definition at one place to avoid code redundancy. This is the scenario where we should use an Abstract class & all subclasses of this Abstract class will get the common definition of these behaviors.

In terms of coding
Create an 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.

Let's have a look at 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 behavior income() but how they earn it, is different i.e. behavior name is the 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 behavior name but able to provide different definitions.

If we use an 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 an interface named 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 makes sense to you & explain to you where we should use Abstract class and where we should use Interfaces.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.