Abstract Class in Java | OOP Concept in Java
An abstract class in Java is a class that cannot be instantiated and is used to declare common characteristics of subclasses. It is designed to be extended by other classes, allowing them to share methods and properties while also implementing their specific functionalities. Abstract classes provide a way to achieve partial abstraction in Java.
Key Points on Abstract Class:
- An abstract class cannot be instantiated; it must be subclassed.
- It can contain abstract methods (methods without a body) as well as concrete methods (methods with a body).
- Subclasses of an abstract class must implement all abstract methods or be declared abstract themselves.
- Abstract classes can have constructors, which are called when a subclass is instantiated.
- They support fields and methods with any visibility, including
public
,protected
, andprivate
. - Abstract classes provide a common base class for subclasses that share a common set of methods and properties.
- They can extend other classes and implement interfaces, but cannot be instantiated directly.
- Unlike interfaces, abstract classes can contain fields that store state.
Syntax of Abstract Class:
Syntax Example
abstract class Animal {
abstract void sound(); // Abstract method
void eat() { // Concrete method
System.out.println("This animal eats food.");
}
}
Example of Abstract Class in Java:
This example demonstrates an abstract class Animal
with an abstract method sound()
and a concrete method eat()
. The Dog
class extends Animal
and provides its own implementation of sound()
.
Code Example
abstract class Animal {
abstract void sound(); // Abstract method
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks.");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Calls overridden method
dog.eat(); // Calls inherited concrete method
}
}
Output
Dog barks.
This animal eats food.
This animal eats food.
Detailed Explanation:
- Abstract Method: An abstract method is a method without a body, declared using the
abstract
keyword. Subclasses must implement this method. - Concrete Method: A method with a body, which can be inherited and used by subclasses.
- Inheritance: Abstract classes are meant to be extended, so subclasses inherit and override its abstract methods to provide specific behavior.
- Instantiation: Since abstract classes are incomplete (with unimplemented methods), they cannot be instantiated directly.
Abstract classes are essential for building a robust class hierarchy, allowing developers to define a common base structure while leaving specific details to be implemented by subclasses.