Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8): Working with Inheritance

Java SE 8 Programmer I (OCAJP 8) · Work through your exam, one topic at a time.

All guide sections

Working with Inheritance

Working with Inheritance

This domain tests extends, implements, constructor chaining, overriding, polymorphism, casting, abstract classes, and interfaces. The central skill is knowing whether the compiler uses the reference type or the object type.

Inheritance rules

  • A class extends one class and implements multiple interfaces. Constructors are not inherited; the first statement of every constructor is super(...) or this(...), inserted as super() when absent.
  • Overriding requires the same signature, a covariant (same or narrower) return type, no reduction in visibility, and no broader checked exceptions. static methods are hidden, not overridden; private, final, and constructors cannot be overridden.
  • A parent reference can refer to a child object. Instance method calls use the object's actual type (virtual dispatch); field access and static method calls use the reference type.
  • Downcasting is explicit and may throw ClassCastException; guard it with instanceof.
  • Abstract classes may have constructors and both abstract and concrete methods. Interfaces declare constants (public static final) and abstract methods; Java 8 adds default and static methods.

Worked example

class A { int x = 1; int getX() { return x; } }
class B extends A { int x = 2; int getX() { return x; } }
A a = new B();
System.out.println(a.x + " " + a.getX());

Field access a.x uses the compile-time type A, so it reads 1. The method call a.getX() dispatches to B, so it returns 2. Output: 1 2.

Traps

  • Calling an overridable method from a constructor can run child code before child fields are initialized.
  • A subclass cannot assign weaker access to an override.
  • super.super is not legal; you cannot skip a level.
  • Interface default method conflicts must be resolved explicitly with InterfaceName.super.method().
  • Casting to an unrelated sibling type fails at runtime even when it compiles.