Object-Oriented Programming: Classes, Inheritance, Interfaces, and Records
Domain 3 tests encapsulation, inheritance mechanics, interface rules and polymorphism: what compiles, what is overridden versus hidden, and the order in which constructors and initializers run.
Classes and access
- Access order:
private< package-private (no modifier) <protected<public.protectedalso grants subclass access across packages, but only through a reference of the subclass type. staticmembers belong to the class and are hidden, not overridden.finalprevents reassignment, overriding or subclassing depending on where it appears.- Initialization order: superclass static blocks, subclass static blocks, superclass instance initializers and constructor, then subclass instance initializers and constructor.
Inheritance
- Every constructor starts with
super(...)orthis(...); the compiler insertssuper()only when neither is written. - Overriding requires the same signature, no more restrictive access, a covariant return type, and no new checked exceptions.
Objectcontracts:equalsandhashCodemust agree; overriding one without the other breaks hash-based collections.
Interfaces and records
- Interfaces may declare
abstract,default,staticand (since Java 9)privatemethods; fields are implicitlypublic static final. - A class inheriting conflicting
defaultmethods must override and can delegate withInterface.super.method(). - Records (Java 16+, outside Java 11 scope) are implicitly
final, extendjava.lang.Record, and generate a canonical constructor, accessors,equals,hashCodeandtoStringfrom their components.
Worked example
class A { A() { print(); } void print() { System.out.print("A"); } }
class B extends A { int x = 7; void print() { System.out.print(x); } }
new B(); // prints 0, not 7
A() executes before B's field initializers, so the overridden print() sees x at its default value.
Traps
- Abstract classes may declare constructors; interfaces may not.
- You cannot reduce visibility when overriding.
staticmethods are not polymorphic; calling one through an instance uses the declared type.