Abstract Classes and Methods

Abstract Class

An abstract class in Java is a class that cannot be instantiated and is meant to be subclassed. It serves as a template for other classes by providing common fields and methods that subclasses can inherit and extend.

Characteristics of Abstract Classes

  • Cannot be instantiated: You cannot create an object of an abstract class.
  • Can have abstract methods: These methods have no body and must be implemented by subclasses.
  • Can have concrete methods: Abstract classes can also have methods with implementations.
  • Can have constructors: Unlike interfaces, abstract classes can have constructors.
  • Can have fields (variables): Both instance and static fields are allowed.

Syntax

Abstract Method

An abstract method is a method that is declared without an implementation (i.e., without a body). It is meant to be overridden in subclasses.

Syntax

Any class that extends an abstract class must implement all its abstract methods, unless it is itself declared abstract.

Implementing Abstract Classes and Methods

To use an abstract class, you must create a subclass that extends the abstract class and provides implementations for its abstract methods.

Example:

  • Animal is an abstract class that defines a blueprint for all animals.
  • Dog extends Animal and implements the makeSound() method.
  • The main method demonstrates creating an instance of the subclass and calling both abstract and concrete methods.