1. Home
  2. Interview Questions
  3. Java
  4. What happens when you cast a subclass object to a superclass…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: Casting a subclass object to a superclass type is generally safe and allows accessing superclass properties but can lead to runtime exceptions if mismanaged.

Detailed explanation

In Java, when you cast a subclass object to a superclass type, you are promoting the object to a higher level of abstraction. This is known as upcasting and is always safe because every instance of a subclass is also an instance of its superclass. When you upcast, you can access only the members (fields and methods) of the superclass. However, if you attempt to downcast a superclass back to a subclass without checking the actual type of the object, this can lead to a ClassCastException at runtime.

Furthermore, to make downcasting safer, you can use the instanceof operator to check if the object you're casting is indeed an instance of the subclass you wish to cast to. For example, if you have a superclass Animal and subclasses Dog and Cat, you can safely cast a Dog object to Animal but should check whether an Animal variable is actually a Dog before downcasting.

Example

class Animal { } class Dog extends Animal { void bark() { System.out.println("Woof!"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Dog(); // Upcasting Dog dog = (Dog) myAnimal; // Downcasting dog.bark(); // Woof! } }

Common mistakes

  • Assuming downcasting is always safe without type checking.
  • Not using instanceof to safeguard against ClassCastException.
  • Confusing upcasting with downcasting in multi-level inheritance scenarios.

Follow-up questions

  • Can downcasting lead to performance issues?
  • What is the difference between implicit and explicit casting?
  • How does polymorphism relate to type casting in Java?

Interview tip: Prepare examples to illustrate your understanding of upcasting and downcasting.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More medium Java questions

All medium questions →

Related Questions

‹
Q4 of 18 · Java
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA