Abstract Class in Java
An abstract class is a class that is declared using the abstract keyword. It is used to achieve partial abstraction in Java.
Key Points
- Any class declared with the abstract keyword is called an abstract class.
- An abstract class can contain:
- An abstract class cannot be instantiated (object creation is not allowed).
- If a class contains at least one abstract method, then the class must be declared abstract.
- An abstract class does not support multiple inheritance.
- An abstract class supports partial abstraction.
Abstract Method
- An abstract method is a method that:
✓Does not have a method body
✓Ends with a semicolon (;)
- Abstract methods only provide method declaration, not implementation.
Concrete Method
- A concrete method is a method that:
✓Has a method body
✓Provides complete implementation
System.out.println("Concrete method");
Types of Abstraction in Abstract Class
1. Partial Abstraction
An abstract class is called partial abstraction when it contains both abstract methods and concrete methods.
abstract void test(); // abstract method
void show() { // concrete method
System.out.println("Hello");
2. No Abstraction
If an abstract class contains only concrete methods, then it is considered as no abstraction.
System.out.println("Only concrete methods");
Why Abstract Class Cannot Be Fully Abstract
- An abstract class cannot be fully abstract because:
- Every abstract class inherits from the Object class
- The Object class contains only concrete methods
- Hence, every abstract class will always contain concrete methods indirectly
- Therefore, an abstract class cannot achieve full abstraction.
Contracts Between Abstract Class and Subclass
Contract 1
If a subclass extends an abstract class, then it must provide implementations for all abstract methods of the abstract class.
👉 Implementation means method overriding
System.out.println("Running");
Contract 2
If a subclass does not implement the abstract methods of the abstract class, then the subclass must also be declared abstract.
abstract class C extends A {
// No implementation provided
Important Notes
- Abstract classes are used to provide a base structure for subclasses.
- They are commonly used in frameworks and APIs.
- Abstract class supports inheritance but not multiple inheritance.
Comments
Post a Comment