Oracle Java Foundations study materials
Oracle Java Foundations study resources

Oracle Java Foundations: Working with Inheritance

Oracle Java Foundations · Work through your exam, one topic at a time.

All guide sections

Working with Inheritance

Basics

A class extends exactly one superclass; interfaces may extend several. Every class ultimately extends Object. Constructors and private members are not inherited. If a subclass constructor does not call super(...) or this(...) explicitly, the compiler inserts super() - which fails to compile if the superclass has no no-argument constructor. Each constructor calls exactly one of them, and only as the first statement.

Overriding rules

An override keeps the signature, may narrow the return type covariantly, may not reduce visibility, may not throw broader checked exceptions, and cannot target final, static, or private methods. static methods are hidden, not overridden - the reference type decides which runs. @Override is optional but catches typos at compile time. Fields are hidden, not overridden.

Polymorphism

With Animal a = new Dog();, instance method calls use the runtime type, while fields and static method calls use the reference type. An upcast is implicit; a downcast needs an explicit cast and throws ClassCastException if wrong. instanceof returns false for null and never throws.

Abstract types and interfaces

An abstract class may hold constructors, fields, and concrete methods but cannot be instantiated; a subclass must implement all abstract methods or itself be abstract. Interface methods are implicitly public abstract; default and static methods have bodies; interface fields are implicitly public static final. A class implements an interface with implements, and there is no diamond problem because conflicting defaults must be resolved.

Worked example

If class A { A(int x) {} }, then class B extends A { } fails to compile (no no-arg super()), while class B extends A { B() { super(1); } } is fine.