What is Abstract Method in Java: Definition and Example
abstract method in Java is a method declared without a body using the abstract keyword. It defines a method signature that must be implemented by subclasses, allowing different classes to provide their own behavior.How It Works
Think of an abstract method as a promise or a placeholder in a class. It tells the program: "Any class that extends me must provide its own version of this method." The abstract method itself has no code inside it, just the method name and parameters.
This is useful when you want to create a general blueprint for a group of classes but leave some details open for each specific class to fill in. The class containing an abstract method must be declared as abstract, and you cannot create objects directly from it.
When a subclass inherits from this abstract class, it must write the actual code for the abstract method. This ensures that every subclass has its own specific behavior for that method, while sharing the common structure from the abstract class.
Example
This example shows an abstract class with an abstract method, and two subclasses that implement it differently.
abstract class Animal { abstract void sound(); // abstract method without body } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal dog = new Dog(); Animal cat = new Cat(); dog.sound(); cat.sound(); } }
When to Use
Use abstract methods when you want to define a common interface or contract for a group of related classes but expect each class to provide its own specific implementation. This is common in frameworks and large programs where you want to enforce certain methods exist but allow flexibility in how they work.
For example, in a drawing program, you might have an abstract class Shape with an abstract method draw(). Each shape like Circle or Rectangle implements draw() differently to show itself on the screen.
Key Points
- An abstract method has no body and is declared with the
abstractkeyword. - It must be inside an abstract class.
- Subclasses must override and provide the method's implementation.
- You cannot create objects of an abstract class directly.
- Abstract methods help enforce a common interface while allowing different behaviors.