Abstract Class in Java: Explain with example

Abstract Class in Java

Abstract Class in Java – an abstract class is a class that cannot be instantiated directly and is meant to be subclassed. It can contain abstract methods, which are methods without a body, and concrete methods, which have an implementation.

Abstract Class in Java

  • An abstract class is declared with the abstract keyword.
  • It can have abstract methods (methods without a body) and concrete methods (methods with a body).
  • It can have member variables and constructors.
  • It cannot be instantiated directly.

Abstract Method in Java

  • An abstract method is declared without an implementation using the abstract keyword.
  • Subclasses must provide implementations for all abstract methods from the abstract superclass unless the subclass is also abstract.

Example

Here’s a simple example to illustrate abstract classes and methods:

// Abstract class
abstract class Animal {
    // Abstract method (does not have a body)
    public abstract void makeSound();
    
    // Regular method
    public void eat() {
        System.out.println("This animal is eating.");
    }
}

// Subclass (inherited from Animal)
class Dog extends Animal {
    public void makeSound() {
        // The body of makeSound() is provided here
        System.out.println("Woof");
    }
}

class Cat extends Animal {
    public void makeSound() {
        // The body of makeSound() is provided here
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        Cat myCat = new Cat();
        
        myDog.makeSound();  // Outputs: Woof
        myDog.eat();        // Outputs: This animal is eating.
        
        myCat.makeSound();  // Outputs: Meow
        myCat.eat();        // Outputs: This animal is eating.
    }
}

Explanation

  • Abstract Class Animal:
    • Declares an abstract method makeSound() which must be implemented by any non-abstract subclass.
    • Implements a concrete method eat() which is inherited by subclasses.
  • Concrete Subclasses Dog and Cat:
    • Both subclasses provide specific implementations for the abstract method makeSound().
  • Main Class:
    • Demonstrates creating instances of Dog and Cat, calling their makeSound() and eat() methods.

This structure allows for defining a common interface in the abstract class while leaving the implementation details to the subclasses.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *