Bird
Raised Fist0
Javaprogramming~15 mins

Abstract classes in Java - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Abstract classes
What is it?
An abstract class in Java is a special type of class that cannot be used to create objects directly. It can have both methods with code (concrete methods) and methods without code (abstract methods). Abstract classes are used to define a common template or blueprint for other classes to follow.
Why it matters
Abstract classes help organize code by providing a shared structure for related classes, ensuring they implement certain behaviors. Without abstract classes, programmers would have to repeat code or rely on less clear designs, making programs harder to maintain and extend.
Where it fits
Before learning abstract classes, you should understand basic classes, objects, and inheritance in Java. After mastering abstract classes, you can explore interfaces, polymorphism, and design patterns that use abstraction.
Mental Model
Core Idea
An abstract class is a blueprint that defines common features and forces subclasses to fill in missing details.
Think of it like...
Think of an abstract class like a recipe template that lists ingredients and steps but leaves some steps blank for the cook to decide how to prepare them.
AbstractClass
┌───────────────┐
│ AbstractClass │
│ ┌───────────┐ │
│ │ methodA() │ │  <-- concrete method with code
│ └───────────┘ │
│ ┌───────────┐ │
│ │ methodB() │ │  <-- abstract method without code
│ └───────────┘ │
└─────┬─────────┘
      │
      ▼
Subclass
┌───────────────┐
│ Subclass      │
│ ┌───────────┐ │
│ │ methodB() │ │  <-- subclass provides code here
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is an Abstract Class
🤔
Concept: Introduce the idea of a class that cannot create objects but can define methods.
In Java, an abstract class is declared with the keyword 'abstract'. You cannot create an object directly from it. It can have normal methods with code and abstract methods without code. Abstract methods must be implemented by subclasses.
Result
You learn that abstract classes are like incomplete blueprints that need subclasses to finish them.
Understanding that abstract classes cannot be instantiated clarifies their role as templates, not final objects.
2
FoundationDeclaring Abstract Methods
🤔
Concept: Learn how to declare methods without code inside an abstract class.
Inside an abstract class, you can declare abstract methods using the 'abstract' keyword and no method body. For example: 'abstract void draw();'. This means subclasses must provide the actual code for 'draw'.
Result
You see how abstract methods enforce that subclasses implement specific behaviors.
Knowing abstract methods act as placeholders ensures subclasses follow a contract, improving code consistency.
3
IntermediateUsing Concrete Methods in Abstract Classes
🤔
Concept: Abstract classes can have methods with full code alongside abstract methods.
An abstract class can include normal methods with code that subclasses inherit. For example, a method 'printDetails()' can be fully defined in the abstract class and used by all subclasses without rewriting it.
Result
You realize abstract classes can share common code, reducing duplication.
Understanding that abstract classes combine shared code and required methods helps design flexible and reusable code.
4
IntermediateSubclassing Abstract Classes
🤔Before reading on: Do you think a subclass must implement all abstract methods or can it skip some? Commit to your answer.
Concept: Subclasses must provide code for all abstract methods or themselves be declared abstract.
When a class extends an abstract class, it must implement all abstract methods. If it doesn't, it must also be declared abstract. This ensures no abstract method remains without code in concrete classes.
Result
You learn the rule that concrete subclasses must complete the abstract class's missing parts.
Knowing this rule prevents errors and enforces complete implementations in usable classes.
5
IntermediateAbstract Classes vs Interfaces
🤔Before reading on: Do you think abstract classes and interfaces can both have method implementations? Commit to your answer.
Concept: Understand the difference and overlap between abstract classes and interfaces in Java.
Abstract classes can have both abstract and concrete methods, and can hold state (fields). Interfaces (since Java 8) can have default methods with code but cannot hold instance fields. Abstract classes are for closely related classes; interfaces are for capabilities.
Result
You see when to use abstract classes versus interfaces.
Understanding this distinction helps choose the right tool for code design and maintainability.
6
AdvancedAbstract Classes in Design Patterns
🤔Before reading on: Do you think abstract classes are used only for code reuse or also for enforcing design rules? Commit to your answer.
Concept: Abstract classes often appear in design patterns to enforce structure and reuse.
Patterns like Template Method use abstract classes to define an algorithm's skeleton with some steps abstract. Subclasses fill in the details. This enforces a design contract and promotes code reuse.
Result
You understand abstract classes as a key tool in professional software design.
Knowing abstract classes enable design patterns reveals their power beyond simple inheritance.
7
ExpertAbstract Classes and JVM Bytecode
🤔Before reading on: Do you think abstract classes generate different bytecode than regular classes? Commit to your answer.
Concept: Explore how abstract classes are represented and enforced at the bytecode and JVM level.
In JVM bytecode, abstract classes have the ACC_ABSTRACT flag set. Abstract methods have no code attribute. The JVM prevents instantiation of abstract classes and ensures abstract methods are implemented before use.
Result
You gain insight into how Java enforces abstraction at runtime.
Understanding JVM enforcement helps debug errors related to abstract classes and deepens knowledge of Java internals.
Under the Hood
Abstract classes are compiled into Java bytecode with a special flag marking them as abstract. The JVM checks this flag to prevent creating instances directly. Abstract methods are declared without code in the bytecode, signaling subclasses to provide implementations. At runtime, the JVM enforces that no abstract method remains unimplemented in concrete classes, throwing errors if violated.
Why designed this way?
Java's designers introduced abstract classes to provide a middle ground between full classes and interfaces, allowing shared code and enforced method implementation. This design balances flexibility and safety, preventing incomplete objects and encouraging clear contracts. Alternatives like interfaces alone lacked code reuse, and concrete classes lacked enforcement, so abstract classes fill this gap.
┌───────────────┐
│ AbstractClass │
│ [ACC_ABSTRACT]│
│ abstractMethod│
│  (no code)    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Subclass      │
│ implements    │
│ abstractMethod│
│  (with code)  │
└───────────────┘

JVM prevents:
- Instantiating AbstractClass directly
- Using Subclass if abstractMethod not implemented
Myth Busters - 4 Common Misconceptions
Quick: Can you create an object directly from an abstract class? Commit to yes or no.
Common Belief:You can create objects from an abstract class just like any other class.
Tap to reveal reality
Reality:Abstract classes cannot be instantiated directly; trying to do so causes a compile-time error.
Why it matters:Trying to instantiate an abstract class wastes time and causes errors, blocking program execution.
Quick: Do abstract classes have to contain abstract methods? Commit to yes or no.
Common Belief:An abstract class must have at least one abstract method.
Tap to reveal reality
Reality:An abstract class can have zero abstract methods; it can be abstract simply to prevent instantiation.
Why it matters:Misunderstanding this limits design options and confuses why some classes are abstract.
Quick: Can a subclass skip implementing some abstract methods if it wants? Commit to yes or no.
Common Belief:A subclass can choose which abstract methods to implement and leave others unimplemented.
Tap to reveal reality
Reality:A concrete subclass must implement all abstract methods; otherwise, it must be declared abstract itself.
Why it matters:Failing to implement all abstract methods causes compile errors and incomplete class definitions.
Quick: Are abstract classes and interfaces interchangeable in Java? Commit to yes or no.
Common Belief:Abstract classes and interfaces are the same and can be used interchangeably.
Tap to reveal reality
Reality:They serve different purposes: abstract classes can hold state and code, interfaces define capabilities and cannot hold instance fields.
Why it matters:Confusing them leads to poor design choices and limits code flexibility.
Expert Zone
1
Abstract classes can have constructors, which are called during subclass instantiation, allowing shared initialization.
2
Abstract classes can define protected or private methods to hide implementation details from subclasses or external code.
3
Using abstract classes with generics allows creating flexible and type-safe templates for complex hierarchies.
When NOT to use
Avoid abstract classes when you need to define a contract without shared code or state; use interfaces instead. Also, if multiple inheritance of type is needed, interfaces are better since Java does not support multiple inheritance of classes.
Production Patterns
Abstract classes are widely used in frameworks to provide base classes with default behavior, such as in Java Swing's AbstractButton or in template method patterns where the abstract class defines the algorithm skeleton and subclasses fill in steps.
Connections
Interfaces in Java
Related concept that also defines contracts but without state or constructors.
Understanding abstract classes clarifies when to use interfaces for pure behavior contracts versus abstract classes for shared code and partial implementation.
Template Method Design Pattern
Abstract classes often implement this pattern by defining fixed steps and abstract methods for subclasses.
Knowing abstract classes helps grasp how design patterns enforce structure and reuse in software.
Blueprints in Architecture
Abstract classes serve as blueprints that specify structure but leave details to builders.
Seeing abstract classes as blueprints connects software design to real-world planning and construction.
Common Pitfalls
#1Trying to create an object from an abstract class.
Wrong approach:AbstractClass obj = new AbstractClass();
Correct approach:Subclass obj = new Subclass();
Root cause:Misunderstanding that abstract classes cannot be instantiated directly.
#2Not implementing all abstract methods in a concrete subclass.
Wrong approach:public class Subclass extends AbstractClass { // missing implementation of abstract methods }
Correct approach:public class Subclass extends AbstractClass { @Override public void abstractMethod() { // implementation } }
Root cause:Not realizing that concrete subclasses must provide code for all abstract methods.
#3Declaring an abstract method with a method body.
Wrong approach:abstract void method() { System.out.println("Hello"); }
Correct approach:abstract void method();
Root cause:Confusing abstract methods as methods that can have code; abstract methods must have no body.
Key Takeaways
Abstract classes define a common template with some methods left incomplete for subclasses to implement.
You cannot create objects directly from abstract classes; they serve as blueprints only.
Abstract classes can have both abstract methods without code and concrete methods with code.
Subclasses must implement all abstract methods or be declared abstract themselves.
Abstract classes enable code reuse and enforce design contracts, playing a key role in professional Java programming.

Practice

(1/5)
1. Which statement about abstract classes in Java is true?
easy
A. All methods in an abstract class must be abstract.
B. Abstract classes cannot have any methods with code.
C. Abstract classes are the same as interfaces.
D. You cannot create an object directly from an abstract class.

Solution

  1. Step 1: Understand abstract class instantiation

    Abstract classes cannot be instantiated directly, meaning you cannot create objects from them using new.
  2. Step 2: Check method rules in abstract classes

    Abstract classes can have both abstract methods (without body) and regular methods (with code). So, not all methods must be abstract.
  3. Final Answer:

    You cannot create an object directly from an abstract class. -> Option D
  4. Quick Check:

    Abstract class instantiation = not allowed [OK]
Hint: Remember: abstract classes can't make objects directly [OK]
Common Mistakes:
  • Thinking abstract classes can be instantiated
  • Believing all methods must be abstract
  • Confusing abstract classes with interfaces
2. Which of the following is the correct way to declare an abstract class in Java?
easy
A. abstract class MyClass {}
B. class abstract MyClass {}
C. abstract MyClass class {}
D. class MyClass abstract {}

Solution

  1. Step 1: Recall Java syntax for abstract classes

    The keyword abstract must come before the keyword class in the declaration.
  2. Step 2: Check each option's order

    Only abstract class MyClass {} has the correct order: abstract class MyClass {}. Others have incorrect keyword order.
  3. Final Answer:

    abstract class MyClass {} -> Option A
  4. Quick Check:

    abstract class syntax = 'abstract class' [OK]
Hint: abstract keyword always before class keyword [OK]
Common Mistakes:
  • Placing abstract after class
  • Mixing keyword order
  • Omitting abstract keyword
3. What will be the output of the following code?
abstract class Animal {
    abstract void sound();
    void sleep() {
        System.out.println("Sleeping");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
        a.sleep();
    }
}
medium
A. Sleeping\nBark
B. Compilation error
C. Bark\nSleeping
D. Runtime error

Solution

  1. Step 1: Understand method calls on abstract class reference

    The variable a is of type Animal but refers to a Dog object. Calling sound() calls Dog's implementation, printing "Bark".
  2. Step 2: Call the concrete method from abstract class

    Calling sleep() uses the method defined in Animal, printing "Sleeping".
  3. Final Answer:

    Bark Sleeping -> Option C
  4. Quick Check:

    Dog sound then Animal sleep = Bark then Sleeping [OK]
Hint: Abstract ref calls subclass method, regular method runs as is [OK]
Common Mistakes:
  • Expecting compilation error for abstract class reference
  • Confusing method call order
  • Thinking abstract class methods can't be called
4. Identify the error in the following code:
abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing Circle");
    }
}

class Square extends Shape {
}

public class Test {
    public static void main(String[] args) {
        Shape s = new Square();
        s.draw();
    }
}
medium
A. Square class must implement the abstract method draw()
B. Cannot create object of abstract class Shape
C. Method draw() in Circle should be abstract
D. No error, code runs fine

Solution

  1. Step 1: Check abstract method implementation in subclasses

    The abstract method draw() in Shape must be implemented by all non-abstract subclasses.
  2. Step 2: Verify Square class implementation

    The Square class does not implement draw() and is not declared abstract, causing a compilation error.
  3. Final Answer:

    Square class must implement the abstract method draw() -> Option A
  4. Quick Check:

    All abstract methods must be implemented in concrete subclasses [OK]
Hint: All abstract methods must be implemented or class must be abstract [OK]
Common Mistakes:
  • Forgetting to implement abstract methods
  • Thinking abstract class objects can be created
  • Marking implemented methods as abstract
5. You want to design a system where different types of vehicles share a common method startEngine() but each vehicle starts differently. Which approach using abstract classes is best?
hard
A. Make Vehicle a concrete class with startEngine() implemented, subclasses override it if needed.
B. Make an abstract class Vehicle with an abstract method startEngine(), then subclasses implement it.
C. Make Vehicle an interface with startEngine() method, implemented by subclasses.
D. Make Vehicle a final class with startEngine() method.

Solution

  1. Step 1: Understand the need for shared method with different implementations

    Since startEngine() must be shared but implemented differently, an abstract method enforces subclasses to provide their own version.
  2. Step 2: Choose abstract class with abstract method

    Declaring Vehicle as abstract with abstract startEngine() ensures all subclasses implement it, sharing the concept but customizing behavior.
  3. Final Answer:

    Make an abstract class Vehicle with an abstract method startEngine(), then subclasses implement it. -> Option B
  4. Quick Check:

    Abstract class with abstract method enforces implementation [OK]
Hint: Use abstract method to force subclass-specific behavior [OK]
Common Mistakes:
  • Using concrete method without forcing override
  • Confusing interfaces with abstract classes
  • Making class final prevents subclassing