Abstraction allows us to hide our implementation. It is one of the key properties of Object-Oriented Programming (OOP). In java, it is implemented using abstract class & Interface.
Abstract class
We can simply create an abstract class by including the abstract
keyword in front of it. An abstract class cannot be instantiated. So no objects of an abstract class or constructors are allowed.
abstract class Animal {
int type;
abstract void move();
}
Interface
The interface is a blueprint of a class that is used to specify its behavior. Again an interface cannot be instantiated. It can have only abstract functions. It cannot have any function body. So we don't need to specify the abstract
keyword.
interface Shape{
String color;
void draw();
}
When to use Abstract Class?
If we have a use case where "A is a B" consider using an abstract class.
Eg- Lion is an Animal , Neem is a Tree
When to use interface?
If we have a use case where "A can do some activity of B" consider using an abstract class.
Eg- Scream can give the sound of an Animal , Blossom can give a flower of a Tree