OCP exam prep: abstract classes¶
☕ Java 17 · 🎓 OCP 1Z0-829 · Blueprints You Can't Instantiate
Optional page
This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.
Exam objective: Create classes, and implement polymorphism by differentiating object type versus reference type.
Four traps to watch for¶
Trap 1 — Modifier order
abstract public and public abstract are both fine. abstract after the word class, or after a method's return type, is an error.
Trap 2 — Braces mean a body
An abstract method never has { }, not even empty. A method without abstract always needs a body.
Trap 3 — Forbidden partners
abstract never goes with final, private or static.
Trap 4 — Zero abstract methods
An abstract class doesn't need any abstract method, and it still can't be created with new. When a question uses abstract, check the whole family before answering.
Practice questions¶
1. Which lines fail to compile?
1: abstract class Trailer {
2: abstract int length();
3: abstract void play() { }
4: public abstract String name();
5: void stop();
6: abstract static void reset();
7: }
A. Lines 3 and 5
B. Lines 3, 5 and 6
C. Lines 2, 4 and 6
D. Line 5 only
Answer
B. Line 3 is abstract but has a body. Line 5 has no body but isn't abstract. Line 6 combines abstract and static. Lines 2 and 4 are valid: public before abstract is legal.
2. Which classes fail to compile?
abstract class Content { abstract String format();
abstract int minutes(); }
abstract class Series extends Content {
int minutes() { return 45; } }
class Anime extends Series { }
class Documentary extends Content {
String format() { return "4K"; } }
A. Anime only
B. Documentary only
C. Anime and Documentary
D. Series, Anime and Documentary
Answer
C. Anime is the first concrete class of its family and forgets format(). Documentary extends Content directly and forgets minutes() (it was Series that implemented it). Series is abstract, so it may leave methods unimplemented.
3. What does System.out.print(new Movie().format()) print?
abstract class Content {
Content() { System.out.print("A"); }
abstract String format(); }
class Movie extends Content {
Movie() { System.out.print("B"); }
String format() { return "C"; } }
A. BC
B. ABC
C. AC
D. Does not compile
Answer
B. new Movie() runs the Content constructor first through the implicit super() (A), then the Movie constructor body (B). format() returns C, which main prints.