Abstract Class
An abstract class in Java is a class that cannot be instantiated and is meant to be subclassed. It serves as a template for other classes by providing common fields and methods that subclasses can inherit and extend.
Characteristics of Abstract Classes
- Cannot be instantiated: You cannot create an object of an abstract class.
- Can have abstract methods: These methods have no body and must be implemented by subclasses.
- Can have concrete methods: Abstract classes can also have methods with implementations.
- Can have constructors: Unlike interfaces, abstract classes can have constructors.
- Can have fields (variables): Both instance and static fields are allowed.
Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
abstract class Animal { String name; // Constructor Animal(String name) { this.name = name; } // Abstract method (no body) abstract void makeSound(); // Concrete method (has body) void sleep() { System.out.println(name + " is sleeping."); } } |
Abstract Method
An abstract method is a method that is declared without an implementation (i.e., without a body). It is meant to be overridden in subclasses.
Syntax
1 2 3 4 |
abstract class Shape { // Abstract method abstract void draw(); } |
Any class that extends an abstract class must implement all its abstract methods, unless it is itself declared abstract.
Implementing Abstract Classes and Methods
To use an abstract class, you must create a subclass that extends the abstract class and provides implementations for its abstract methods.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// Abstract class abstract class Animal { String name; Animal(String name) { this.name = name; } // Abstract method abstract void makeSound(); // Concrete method void eat() { System.out.println(name + " is eating."); } } // Concrete subclass class Dog extends Animal { Dog(String name) { super(name); } // Implementing the abstract method @Override void makeSound() { System.out.println(name + " barks."); } } // Main class public class AbstractDemo { public static void main(String[] args) { Dog dog = new Dog("Buddy"); dog.makeSound(); // Output: Buddy barks. dog.eat(); // Output: Buddy is eating. } } |
Animal
is an abstract class that defines a blueprint for all animals.Dog
extendsAnimal
and implements themakeSound()
method.- The main method demonstrates creating an instance of the subclass and calling both abstract and concrete methods.