An abstract class in Java is a class that cannot be instantiated directly. It can have both abstract (methods without a body) and concrete (methods with a body) methods. Abstract classes are used when a base class provides a common structure for its derived classes, but the derived classes are expected to provide specific implementations of certain methods.
Characteristics of an Abstract Class
1. It can have abstract methods (methods without implementation).
2. It can have concrete methods (methods with implementation).
3. An abstract class can have fields (variables), constructors, and static methods.
4. A class that contains an abstract method must be declared abstract.
5. Abstract classes can extend other abstract or concrete classes.
Important Points about Abstract Methods
1. No Implementation: An abstract method doesn’t contain any code in its body.
2. Must be Implemented: Any subclass or implementing class is required to provide the method’s implementation.
3. Declared in Abstract Classes or Interfaces: Abstract methods are defined in abstract classes or interfaces. You can’t create objects of an abstract class directly; they are meant to be extended by subclasses.
4. Used for Defining a Template: Abstract methods define a template for other classes to follow and implement.
Syntax of Abstract Method:
abstract returnType methodName();
Syntax of Abstract class:
abstract class A {
abstract void myMethod(); // Abstract method does not have body
void normalMethod() { // Concrete method
// put the content here
}
}
Example:
// Abstract class Animal
abstract class Animal {
// Abstract method (does not have a body)
abstract void makeSound();
// Regular method (does have a body)
public void eat() {
System.out.println("Animal eat food.");
}
}
// Concrete class Dog that extends Animal
class Dog extends Animal {
// Providing implementation for abstract method makeSound()
void makeSound() {
System.out.println("Dog bark");
}
}
// Main class to test the code
public class Main {
public static void main(String[] args) {
// Creating an object of Dog class
Animal dog = new Dog();
dog.makeSound(); // Calls Dog's makeSound() method
dog.eat(); // Calls eat() method from Animal class
}
}
Explanation:
- Animal is an abstract class with one abstract method makeSound() and one concrete method eat().
- Dog is a concrete class that extends Animal and provides an implementation for the abstract method makeSound().
- You can’t instantiate Animal directly, but you can create an object of Dog and access the methods.
Output:
Animal eat food.
When to Use Abstract Classes?
There are many points so that we can check when to use Abstract Classes.
1. When you want to provide common behavior for subclasses.
2. When there is shared code among all implementations.
3. When you want to define some default implementation for certain methods.