In Java, an abstract class serves as a blueprint for other classes. It cannot be instantiated directly (meaning we cannot create objects of abstract classes). Instead, it provides a foundation for its subclasses to build upon. Let’s dive into the details with an example:
1.Declaring an Abstract Class:
We use the abstract keyword to declare an abstract class. For instance:
abstract class Language {
// Fields and regular methods can be included here
}
2. Abstract Methods:
An abstract method is a method without an implementation (i.e., no body). We use the same abstract keyword to create abstract methods.
For example:
abstract void display();
3.Creating Subclasses:
Although abstract classes cannot be directly instantiated, we can create subclasses from them.
In the following example, we define an abstract class called Language with a regular method display():
Java
abstract class Language {
public void display() {
System.out.println(“This is Java Programming”);
}
}
4. Inheriting from the Abstract Class:
We create a subclass called Main that inherits from the Language class.
Notice how we access the method of the abstract class using an object of the Main class:
class Main extends Language {
public static void main(String[] args) {
Main obj = new Main();
obj.display(); // Output: “This is Java Programming”
}
}
5.Implementing Abstract Methods:
If an abstract class includes any abstract methods, all child classes must provide implementations for those methods.
In the example below, we define an abstract class Animal with an abstract method makeSound() and a non-abstract method eat():
abstract class Animal {
abstract void makeSound();
public void eat() {
System.out.println(“I can eat.”);
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println(“Bark bark”);
}
}
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.makeSound(); // Output: “Bark bark”
d1.eat(); // Output: “I can eat.”
}
}
In this example, Dog provides an implementation for the abstract method makeSound(), satisfying the requirement of the abstract superclass Animal.
Remember that abstract classes allow us to define common behavior and enforce certain methods to be implemented by their subclasses. They play a crucial role in Java’s inheritance hierarchy!