Java Abstract Classes and Abstract Methods (OCP 21)
Java abstract classes for the OCP 21 exam: declaring abstract classes and methods, the first concrete subclass rule, constructors in abstract classes, anonymous subclasses, illegal modifier combinations (abstract with final, private or static) and the syntax traps the exam loves.
kvi5hnuCode Sprout team member7 min readOn this page
Sometimes a parent class exists only to be extended. A generic Shipment, for example, should never be created on its own, only a Parcel or a Pallet. Marking the class abstract expresses exactly that. It also lets the class declare abstract methods, which every concrete subclass is forced to implement.
Abstract classes
An abstract class is declared with the abstract modifier. It can't be instantiated directly:
public abstract class Instrument { }
public class Violin extends Instrument { }
Instrument a = new Violin(); // fine: the object is a Violin
Instrument b = new Instrument(); // DOES NOT COMPILE: Instrument is abstract; cannot be instantiated
Apart from that, an abstract class is a normal class. It can have instance and static fields, constructors, concrete methods (including final and static ones), initializers, nested types and even a main method. It's also allowed to have no abstract methods at all. It still can't be instantiated.
Abstract methods
An abstract method has the abstract modifier and no body. Its declaration ends with a semicolon:
public abstract class Instrument {
public abstract String sound(); // no body
public void play() { System.out.println(sound()); } // concrete method using it
}
public class Drum extends Instrument {
@Override public String sound() { return "boom"; }
}
Instrument i = new Drum();
i.play(); // boom
play() is written once in the parent, and each subclass supplies its own sound(). Polymorphism picks the right version at run time. This is the template method pattern: the abstract class fixes the steps, and the subclasses fill in the blanks.
The rules:
- Only instance methods can be abstract. Abstract fields, constructors, static methods and initializers don't compile.
- An abstract method may appear only in an abstract class (or an interface, chapter 7). A concrete class that declares one fails with "X is not abstract and does not override abstract method m() in X".
- Implementing an abstract method is overriding, so all four overriding rules apply (article 34): same signature, same or wider access, no new or broader checked exceptions, and a covariant return type.
- You can't call an abstract method through
super.super.sound()fails with "abstract method sound() in Instrument cannot be accessed directly".
The first concrete subclass rule
A concrete class is any non-abstract class. The first concrete class in an inheritance chain must implement every abstract method it inherits that nobody above it has implemented yet. Abstract classes in the middle of the chain may implement some of them, all of them, or none.

abstract class Shipment {
abstract String carrier();
abstract double weightKg();
}
abstract class Parcel extends Shipment {
String carrier() { return "PostCo"; } // implements one; weightKg() stays abstract
}
class SmallParcel extends Parcel {
double weightKg() { return 0.8; } // OK: only weightKg() is still owed
}
class Pallet extends Shipment {
String carrier() { return "FreightLine"; } // DOES NOT COMPILE:
} // Pallet doesn't implement weightKg()
Once a method has been implemented, it's inherited as a concrete method. SmallParcel may override carrier(), but it doesn't have to.
If the middle class Parcel weren't abstract, Parcel would become the first concrete class, and it would fail because it doesn't implement weightKg().
The reverse direction works too. An abstract class can extend a concrete class, and it can even re-declare an inherited concrete method as abstract. That forces its own subclasses to provide a fresh implementation:
class Base { public String toString() { return "base"; } }
abstract class Strict extends Base {
public abstract String toString(); // re-abstracted
}
class Leaf extends Strict { } // DOES NOT COMPILE: must implement toString()
Constructors in abstract classes
An abstract class has constructors like any other class. If you don't write one, the compiler adds the default constructor. Its constructors run only as part of creating a concrete subclass object, through super(...):
abstract class Snack {
abstract CharSequence crunch();
Snack() { System.out.println(crunch()); } // calls the subclass's implementation
}
public class Pretzel extends Snack {
String crunch() { return "crunch!"; } // covariant: String is a CharSequence
public static void main(String[] args) { new Pretzel(); } // prints crunch!
}
Calling an abstract method from a constructor compiles and works here, because an implementation always exists by the time any constructor runs. The subclass's fields, though, aren't initialized yet (article 33). If crunch() returned a field of Pretzel, it would return null.
Invalid declarations the exam likes
Abstract method syntax is tested by spotting what's broken:
public abstract class Kite {
public abstract long lift() // DOES NOT COMPILE: missing ;
public abstract void fly() { } // DOES NOT COMPILE: abstract methods cannot have a body
public abstract int tail() { return 1; } // DOES NOT COMPILE: body again
public abstract void spin; // DOES NOT COMPILE: missing ()
public void land(); // DOES NOT COMPILE: missing method body, or declare abstract
public abstract String color; // DOES NOT COMPILE: modifier abstract not allowed here
}
Where you put the modifier also matters. abstract may come before or after the access modifier, but it must come before class and before the return type:
abstract public class Kite { abstract public int lines(); } // compiles
public class abstract Kite { } // DOES NOT COMPILE
public abstract class Kite { public int abstract lines(); } // DOES NOT COMPILE
Illegal modifier combinations
Each of these produces "illegal combination of modifiers". Every combination contradicts the idea that the method will be implemented by a subclass:
| Combination | Why it can't work |
|---|---|
abstract final (class or method) | abstract needs a subclass or override, and final forbids one |
abstract private (method) | private methods aren't inherited, so no subclass can implement them |
abstract static (method) | static methods can't be overridden, only hidden |
abstract synchronized / abstract native | these describe a body, and abstract methods have none |
private final on a method is legal, just redundant, because a private method can't be overridden anyway.
Implementations must still obey access rules:
abstract class Speaker { protected abstract void announce(); }
class Intercom extends Speaker {
private void announce() { } // DOES NOT COMPILE: weaker access than protected
}
Abstract class or interface?
Chapter 7 introduces interfaces, which can also declare abstract methods and, since Java 8, default and static methods. Use an abstract class when subclasses share state (fields) or constructor logic, or need non-public members. A class can extend only one class, but it can implement many interfaces. For a closed set of known subtypes, current Java also offers sealed classes (chapter 7), which are often combined with abstract.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Sealed classes (article 40) are often a better fit than an open abstract class when you know every subclass in advance.
Exam traps from this article
A complete example
This program models shipments with an abstract base class that holds shared state, a constructor, a final template method and two abstract methods. An abstract middle class, two concrete classes and an anonymous subclass complete the hierarchy.
import java.util.List;
import java.util.Locale;
public class Solution {
// Abstract: can't be instantiated, but has state, a constructor and concrete methods
abstract static class Shipment {
private final String id;
private static int created;
Shipment(String id) {
this.id = id;
created++;
}
// the "template": fixed steps, subclasses fill in the blanks
final String label() {
return id + " | " + carrier() + " | " + String.format(Locale.ROOT, "%.2f", cost()) + " EUR";
}
abstract String carrier(); // no body, ends with ;
abstract double weightKg();
double cost() { // concrete, may be overridden
return 4.0 + weightKg() * 1.5;
}
static int created() { return created; }
}
// Still abstract: implements one abstract method, leaves weightKg() open
abstract static class Parcel extends Shipment {
Parcel(String id) { super(id); }
@Override
String carrier() { return "PostCo"; }
}
// First concrete class: must implement everything still abstract
static class SmallParcel extends Parcel {
SmallParcel(String id) { super(id); }
@Override
double weightKg() { return 0.8; }
}
static class Pallet extends Shipment {
private final double kg;
Pallet(String id, double kg) {
super(id);
this.kg = kg;
}
@Override String carrier() { return "FreightLine"; }
@Override double weightKg() { return kg; }
@Override double cost() { return 60.0 + kg * 0.2; } // replaces the default formula
}
public static void main(String[] args) {
// new Shipment("X"); // would not compile: Shipment is abstract
Shipment courier = new Shipment("C-3") { // anonymous concrete subclass
@Override String carrier() { return "BikeMessenger"; }
@Override double weightKg() { return 0.2; }
};
List<Shipment> all = List.of(new SmallParcel("P-1"), new Pallet("L-2", 350), courier);
for (Shipment s : all) {
System.out.println(s.label());
}
System.out.println("Shipments created: " + Shipment.created());
System.out.println("Pallet is a Shipment: " + (all.get(1) instanceof Shipment));
System.out.println("Anonymous class name is empty: " + courier.getClass().getSimpleName().isEmpty());
}
}
Output:
P-1 | PostCo | 5.20 EUR
L-2 | FreightLine | 130.00 EUR
C-3 | BikeMessenger | 4.30 EUR
Shipments created: 3
Pallet is a Shipment: true
Anonymous class name is empty: true
Points to notice:
Shipmenthas a constructor, aprivate finalfield and a static counter. Abstract classes can hold real state.label()isfinal, so subclasses can't change the template, only the blanks it calls (carrier(),weightKg()andcost()).Parcelis abstract and implements onlycarrier().SmallParcel, the first concrete class below it, suppliesweightKg().Palletimplements both abstract methods and also overrides the concretecost().- The anonymous subclass counts as a third concrete class. Its simple name is empty.
Common questions
Can an abstract class have a constructor if it can never be instantiated?
Yes. The constructor initializes the abstract class's part of every subclass object, and subclasses call it with super(...).
Can an abstract class implement an interface without implementing its methods? Yes. The interface's abstract methods simply stay open until the first concrete class (chapter 7).
Can a final class have abstract methods?
No. A final class is never extended, so its abstract methods could never be implemented, and the class would have to be abstract as well, which isn't allowed together with final.
Are abstract classes still used in modern Java?
Yes, especially for template methods and for sharing state. JDK classes such as AbstractList, InputStream and Number are abstract. For pure contracts, interfaces with default methods are usually preferred.
Summary
abstractclasses can't be instantiated, and they may contain any members, including zero or more abstract methods.- Abstract methods have no body, end with
;, exist only in abstract classes (or interfaces), and are implemented by overriding. - The first concrete subclass must implement every inherited abstract method still open. Abstract classes in between may implement any subset, and may re-abstract concrete methods.
- Abstract classes have constructors, which run through
super(...)when a concrete subclass is created. abstractcan't be combined withfinal,private,static,synchronizedornative.
Practice quiz
Test yourself with the abstract classes quiz: 10 exam-style questions with explanations.
Previous: Java Method Overriding and Hiding: Rules, final Methods and Static Hiding (OCP 21)
Related reading
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.