When to use Abstract Class?
2 min readMay 4, 2019
What is an Abstract class?
In Layman terms: An incomplete class is called an Abstract class.
When to use?
An abstract class is best suited for the scenarios where there is a lot of reusable code which you don’t want to write again and again + There are a few things which are specific to each class.
ie Common things + Uncommon things = Abstract class
Example?
Ceremony:
Common things: Sing Anthem, Hoist Flag, etc.
Specific things: Indian Flag, Indian anthem(For India), China Flag, China anthem(For China), etc.
Sample Code?
Abstract class:
public abstract class BaseCeremony{
Flag natonalFlag;
Anthem anthem;
//**** Common Task ******//
public void startCeremony(){
configure();
hoistFlag();
singAnthem();
}
public void hoistFlag(){
natonalFlag.hoist();
}
public void singAnthem(){
anthem.anthem();
}
private void configure(){
natonalFlag = provideFlag();
anthem = provideAnthem();
}
//**** Differs in all part ******//
public abstract Flag provideFlag();
public abstract Anthem provideAnthem();
}
Implementation:
public class IndianCeremony extends BaseCeremony{
public Flag provideFlag(){
return new IndianFlag();
}
public Anthem provideAnthem(){
return new IndianAnthem();
}
}
Extra points: Just for you
- An abstract class is an incomplete class that is why you can not create its objects.
- An abstract class should have at least one abstract method to qualify as an abstract class
- Example of abstract class implementation in Android
Putting up content takes a lot of time and effort 😓.
👏 clap 👏 If you think you learned something from this article.You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.