🧬 Inheritance & Polymorphism
18 Java concepts, each explained step by step with real code, a common trap and practice questions.
- extends & is-aA subclass inherits non-private members; single class inheritance.
- supersuper.method() and super(...) constructor calls.
- Constructor order in hierarchiesParent constructor runs before child; implicit super().
- Method overridingSame signature, covariant return, cannot reduce visibility or widen checked exceptions.
- @OverrideLets the compiler catch accidental overloads and typos.
- Dynamic dispatchThe runtime object type decides which overridden method runs.
- Overloading vs overridingOverloads are chosen at compile time by declared types; overrides at runtime.
- Upcasting & downcastingImplicit upcasts, explicit downcasts and ClassCastException.
- instanceof & pattern matchingif (o instanceof String s) binds a typed variable.
- Field hiding & static method hidingFields and static methods are not polymorphic.
- final classes & methodsPreventing extension and overriding.
- Abstract classesCannot be instantiated; may mix abstract and concrete methods and hold state.
- The Object classRoot of all classes: equals, hashCode, toString, getClass, clone, wait/notify.
- equals() contractReflexive, symmetric, transitive, consistent, x.equals(null) is false.
- hashCode() contractEqual objects must have equal hash codes; override both together.
- Composition over inheritancehas-a vs is-a, fragile base class problem.
- Liskov SubstitutionSubtypes must be usable wherever the parent is expected.
- Calling overridable methods in constructorsSubclass fields are not yet initialized — a classic trap.