Down Casting in Java: Definition, Rules, and Examples

Down Casting in Java

Down Casting is the process of converting a superclass reference (that actually refers to a subclass object) into a subclass reference.

Key Points

  • Down casting is also known as explicit casting.
  • It must be performed by the programmer using a cast operator.
  • The compiler does not perform down casting automatically.
  • Up casting must occur before down casting.
  • If down casting is done without a valid up cast, it results in a ClassCastException at runtime.

Example

class Parent {
    void show() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    void display() {
        System.out.println("Child method");
    }
}

Parent p = new Child(); // Up casting
Child c = (Child) p; // Down casting

c.show(); // Allowed
c.display(); // Allowed

Invalid Down Casting

Parent p = new Parent();
Child c = (Child) p; // ClassCastException

Why Down Casting Is Risky

  • Performed at runtime, not compile time.
  • Can throw ClassCastException if the object is not actually a subclass object.
  • Should be used carefully.

Safe Down Casting (Using instanceof)

if (p instanceof Child) {
    Child c = (Child) p;
    c.display();
}

Summary

  • Down casting = Superclass reference → Subclass reference
  • Explicitly done by programmer
  • Requires prior up casting
  • Can cause runtime exception if done incorrectly

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know