Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 10, 2022 05:59 pm GMT

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

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


Original Link: https://dev.to/sanjaybabu/day-10-how-is-abstraction-achieved-in-java-1plg

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To