Abstraction in Java

Mannan Ul Haq
0
Abstraction is a key principle in object-oriented programming (OOP) that refers to the concept of hiding the complexity and only showing the essential features of the object. In Java, abstraction can be achieved through abstract classes and interfaces (which will be the subject of in-depth discussion in the later tutorial).

Abstract Classes:

An abstract class in Java is a class that cannot be instantiated, meaning you cannot create an object of an abstract class directly. It is designed to act as a base class (or parent class) for other classes. An abstract class can have both abstract and non-abstract methods (methods with implementations).

Abstract methods in Java are declared without an implementation — they don't have a method body. Abstract classes provide a generic structure that other concrete classes follow. Here's a simple example:

abstract class Vehicle
{
    public abstract void run();

    public void changeGear()
    {
        System.out.println("Gear changed");
    }
}

In this example, Vehicle is an abstract class with one abstract method run and one non-abstract method changeGear.


Abstract Methods:

Abstract methods are declared in an abstract class, and they don't have any implementation in the abstract class itself. They are meant to be overridden in the sub classes.

Here's an example of a Car class that inherits from Vehicle and implements the abstract methods:

class Car extends Vehicle
{
    public void run()
    {
        System.out.println("Car is running");
    }
}

The Car class is a concrete class (i.e., it is not abstract) and therefore it must provide an implementation for the run methods.
NOTE: Sub classes that inherit from the abstract class are responsible for providing an implementation for these abstract methods. If a sub class does not provide implementations for all of the abstract class's abstract methods, then the sub class must also be declared as abstract.(alert-success)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !