Advertisement

Abstraction

Abstraction in Object Oriented Programming


Abstraction is a principle of object-oriented programming that involves exposing only the essential features of an object and hiding the implementation details. The goal of abstraction is to simplify the interface of an object so that it is easier to use, understand, and maintain.


There are several ways to implement abstraction in object-oriented programming, including the use of abstract classes and methods, interfaces, and encapsulation.


Abstract Classes and Methods:


An abstract class is a class that contains one or more abstract methods. An abstract method is a method that has a declaration but no implementation. Abstract methods are implemented by subclassing the abstract class and providing implementations for the abstract methods. This allows the abstract class to provide a common interface for its subclasses, while allowing each subclass to implement the abstract methods in its own way.


For example, consider a simple abstract class called Shape that has an abstract method called area():


abstract class Shape {
    abstract double area();
}


To use this abstract class, you would need to create a subclass that provides an implementation for the abstract method area(). For example, you might create a subclass called Rectangle that calculates the area of a rectangle:


class Rectangle extends Shape {
    double length;
    double width;

     Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
     }
@Override
    double area() {
        return length * width;
     }
}


In this example, the abstract class Shape provides a common interface for calculating the area of a shape, while the subclass Rectangle provides the specific implementation for calculating the area of a rectangle.

Interfaces:

Another way to implement abstraction in object-oriented programming is through the use of interfaces. An interface is a set of related methods with empty bodies, which a class can implement to define the behavior of an object.


For example, consider a simple interface called Movable that has two methods, moveUp() and moveDown():


interface Movable {
    void moveUp();
    void moveDown();
}


To use this interface, you would need to create a class that implements the interface and provides implementations for the methods. For example, you might create a class called Ball that represents a movable ball:


class Ball implements Movable {
    int x;
    int y;

     Ball(int x, int y) {
        this.x = x;
        this.y = y;
        }
@Override
void moveUp() {
     y--;
 }
@Override
void moveDown() {
 y++;
 }
}


In this example, the interface Movable provides a common set of methods for moving an object up and down, while the class Ball provides the specific implementation for moving a ball up and down.


Post a Comment

0 Comments