An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To