DEV Community

Cover image for Day 10 - How is abstraction achieved in java?
C K Sanjay Babu
C K Sanjay Babu

Posted on • Originally published at blog.sanjaybabu.dev on

Day 10 - How is abstraction achieved in java?

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();
}

Enter fullscreen mode Exit fullscreen mode

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();
}

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)