Abstract Class in Java

An abstract class is a class that cannot be instantiated on its own and is meant to be subclassed. It serves as a blueprint for other classes, providing a common structure that derived classes can implement or override.

Key Characteristics:

  • Cannot Be Instantiated: You cannot create an instance of an abstract class directly. It must be subclassed, and only the subclasses can be instantiated.
  • Abstract Methods: An abstract class can have abstract methods, which are declared without an implementation (i.e., no method body). Subclasses must provide implementations for these abstract methods.
  • Concrete Methods: An abstract class can also have concrete methods with implementations that can be inherited by subclasses.
  • Instance Variables: Like regular classes, abstract classes can have instance variables.
  • Constructor: Abstract classes can have constructors, which are called when an instance of a subclass is created.
  • Access Modifiers: Abstract classes can be declared with access modifiers (public, protected, default).
  • Polymorphism: Abstract classes are used to achieve polymorphism in Java, allowing a common interface for a group of related classes.
Code Example
Output
Buddy says: Woof Woof
Buddy is eating.
Whiskers says: Meow Meow
Whiskers is eating.

Explanation

  • Abstract Class Animal: This class cannot be instantiated. It has an abstract method makeSound() that must be implemented by any subclass. It also has a concrete method eat() that can be inherited by subclasses.
  • Subclasses Dog and Cat: These classes extend the Animal class and provide implementations for the abstract method makeSound().
  • Main Class: In the Main class, we create instances of Dog and Cat, and call their methods to demonstrate the functionality.