0Pricing
Java Academy · Lesson

Up/Down Casting & instanceof

Understand upcasting to a parent type, safe downcasting with instanceof, and common pitfalls that cause ClassCastException.

Up vs down casting

Upcasting stores a child object in a parent type reference and is always safe. Downcasting goes the other way and needs care. We use instanceof to check the real type at runtime.

Code: upcasting demo

Upcasting is implicit and safe: a Dog can be treated as an Animal. You can call methods declared on Animal; the Dog version runs at runtime.

public class Main {
  static class Animal {
    void speak() { System.out.println("Animal sound"); }
  }
  static class Dog extends Animal {
    void speak() { System.out.println("Woof"); }
    void fetch() { System.out.println("Fetch!"); }
  }

  public static void main(String[] args) {
    // Upcasting: Dog stored in an Animal reference (safe, automatic)
    Animal a = new Dog();
    a.speak();  // calls Dog's speak() due to dynamic binding

    // a.fetch(); // Not allowed: reference is Animal, which does not declare fetch
    System.out.println("Upcasting hides Dog-only methods from the reference type.");
  }
}

All lessons in this course

  1. Abstract Classes
  2. Interfaces (intro & contrasts)
  3. Up/Down Casting & instanceof
← Back to Java Academy