Kindly wait a moment, post will be visible in just 5 seconds.

No Preview

Kamran Hassan

Posted on 8 March 2023

Explain Abstraction in Java

Ad Banner

Abstraction is one of the key principles of object-oriented programming, which allows you to hide the complexity of an object's implementation and expose only the essential features to the users. In Java, you can achieve abstraction using abstract classes and interfaces.
Here are some examples of using abstraction in Java:

Abstract Class Example

In this example, we're creating an abstract class Animal. The class has a name field and a constructor that initializes the field. The class also has an abstract method makeSound() that is intended to be implemented by the subclasses, and a non-abstract method eat() that prints a message to the console.
By defining the Animal class as abstract, we're indicating that it should not be instantiated directly. Instead, we expect the subclasses to provide the implementation for the abstract method makeSound().

Interface Example

In this example, we're creating an interface Shape. The interface defines two abstract methods getArea() and getPerimeter(), which represent the common behavior for all shapes. Any class that implements the Shape interface must provide the implementation for these methods.


Polymorphism Example

In this example, we're creating two subclasses Dog and Cat that extend the Animal abstract class. Both subclasses implement the abstract method makeSound() with their own implementation.
In the Main class, we're creating two objects dog and cat of type Animal, but their actual type is Dog and Cat respectively. We're using polymorphism to call the makeSound() method on each object, which calls the implementation defined in the respective subclass.

By using abstraction, we're able to create a common interface for objects of different types, which makes the code more flexible and easier to maintain.

1

10

0

No Preview

Kamran Hassan

Explore more similar Post

1 Comments

Rizwan Khan

11 April 2023

Thanks for sharing Kamran

0
REPLY