Abstract Keyword

Abstract Keyword

                                                                                                              -Vedant. M. Pandit 

The abstract keyword in Java is used to create abstract classes and abstract methods. It signals that a class or method is incomplete and is meant to be extended or implemented by other classes

1. Abstract Class:-  An abstract class is a class that can’t be instantiated directly. It acts as a blueprint for other classes. The abstract class can contain both abstract methods (methods without a body) and concrete methods (methods with a body). Child classes that extend the abstract class are required to provide implementations for the abstract methods.

example:-

abstract class Animal

    abstract void sound(); // Abstract method, no body here void eat()

        System.out.println("This animal is eating."); 

    

}


2. Abstract Method:- An abstract method is a method that is declared without any implementation (i.e., no code in the method body). It serves as a placeholder, and any subclass that extends the abstract class must provide an implementation for this method.

example:-
class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

Use of abstract Keyword:-

The abstract keyword is used when you want to define general behavior that is shared across different classes, but also require subclasses to provide specific functionality. It enforces structure while allowing flexibility.


Comments