The abstract
keyword in Java is one of many access modifiers that determine how classes, methods, and variables can be accessed in your application. Specifically, when you declare a class as abstract
, it means that the class can't be instantiated directly. This means you cannot create an object or an instance of an abstract class directly using the 'new' keyword.
Abstract
classes act more so as a blueprint or template for other classes. They can contain both abstract
methods (methods without a body) and normal
methods (methods with a body). You use them when you want to provide a common interface for different subclasses while also providing some default behavior.
Here is a simple example for better understanding:
abstract class Animal {
abstract void move();
abstract void eat();
//Concrete method
void label(){
System.out.println("Animal's data:");
}
}
class Bird extends Animal{
void move(){
System.out.println("Moves by flying.");
}
void eat(){
System.out.println("Eats birdfood.");
}
}
public class Main{
public static void main(String args[]){
Animal myBird = new Bird();
myBird.label();
myBird.move();
myBird.eat();
}
}
In the code above, Animal
is an abstract class that includes both abstract methods (move
and eat
) and a concrete method (label
). Bird
is a subclass of Animal
and provides the implementation of the abstract methods. To use the methods, an object of Bird
is created, which inherited the capabilities of the abstract class Animal
.
It is good practice to use abstract classes when you want to provide a common template for subclasses to follow, and when you deem it unnecessary or it doesn't make sense for the superclass to have actual instances. This leads to cleaner, more intuitive code.
The keyword abstract
is an essential part of Java's abstraction feature, one pillar of the four major concepts of Object-Oriented Programming in Java (Abstraction, Inheritance, Polymorphism, and Encapsulation). Understanding how it works gives you a powerful tool for managing complexity in larger applications.