Understanding Inheritance

1. Creating Subclasses

Example: extends

public class Animal {
    protected String name;
    public Animal(String name) { this.name = name; }
    public void speak() { System.out.println("..."); }
}
public class Dog extends Animal {
    public Dog(String name) { super(name); }
    @Override public void speak() { System.out.println("Woof"); }
}
RuleDetail
Single inheritanceOne direct superclass; multiple interfaces allowed
Default superjava.lang.Object
InheritsAll non-private members

2. Using super Keyword

FormUse
super.method()Call parent's overridden method
super.fieldAccess parent field (when shadowed)
super(args)Invoke parent constructor (first stmt)

3. Overriding Methods

RequirementDetail
Same signatureName + parameter types
Return typeSame or covariant subtype
AccessSame or wider
Checked exceptionsSame or narrower; cannot add new
Annotation@Override recommended

4. Understanding Method Overriding Rules

Cannot OverrideReason
final methodsLocked
static methodsHidden, not overridden
private methodsNot visible; defines new method
ConstructorsNot inherited

5. Calling Parent Constructors (super())

AspectDetail
PositionFirst statement (or implicit)
Implicit callCompiler inserts super() if no explicit call
No-arg requiredParent must have accessible no-arg constructor (or call explicit)

6. Understanding Constructor Chaining

Constructor chain

Object()
  ↑ super()
Animal(String)
  ↑ super(name)
Dog(String)
  ← new Dog("Rex")
StepAction
1Super constructor chain runs first
2Instance initializers + field defaults run
3Subclass constructor body runs

7. Using final Keyword

Applied toEffect
ClassCannot be subclassed
MethodCannot be overridden
FieldAssignable once
Local var/parameterCannot reassign

8. Understanding Object as Root Class

Inherited MethodOverride?
equals, hashCode, toStringUsually yes
getClass, wait, notifyfinal — cannot
cloneIf implementing Cloneable

9. Working with instanceof and Type Checking

Example: Pattern matching

if (animal instanceof Dog d) {
    d.fetch();
}
FormNotes
x instanceof TReturns boolean
x instanceof T t JAVA 16+Pattern variable; auto-cast

10. Understanding Covariant Return Types

Example: Covariant return

class Shape { Shape copy() { return new Shape(); } }
class Circle extends Shape {
    @Override Circle copy() { return new Circle(); }   // narrower return
}
RuleDetail
Subclass returnMay be subtype of parent's return type
Caller benefitNo cast needed when calling on subtype reference

11. Understanding Method Overloading vs Overriding

AspectOverloadingOverriding
ScopeSame classSubclass replaces parent
SignatureDifferent paramsSame params
Return typeAnySame/covariant
ResolutionCompile-time (static)Runtime (dynamic)
PolymorphismCompile-timeRuntime