What is type casting in OOP?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid OOP Concepts basics — a prerequisite for any developer role.
Answer
Type casting converts an object reference from one type to another. In OOP, this is primarily relevant for class hierarchies. Two directions: Upcasting (implicit, always safe): cast a subclass reference to a superclass type. No explicit cast needed. Always succeeds — subclass IS-A superclass: Dog myDog = new Dog(); Animal animal = myDog; // Upcast -- implicit and safe animal.speak(); // Calls Dog's speak() via polymorphism animal.fetch(); // ERROR! -- Animal type doesn't have fetch() even though object is a Dog. Downcasting (explicit, potentially unsafe): cast a superclass reference to a subclass type. Must be explicit. Fails with ClassCastException if the object isn't actually that type: Animal animal = new Dog(); // We know it's a Dog Dog dog = (Dog) animal; // Explicit downcast -- works dog.fetch(); // Now we can call Dog-specific methods // Dangerous: Animal animal2 = new Cat(); Dog dog2 = (Dog) animal2; // ClassCastException at runtime!. instanceof operator (safe check before downcast): Animal animal = getAnimal(); if (animal instanceof Dog) { Dog dog = (Dog) animal; // Safe! dog.fetch(); } // Modern Java 16+ pattern matching: if (animal instanceof Dog dog) { // No separate cast! dog.fetch(); }. Python duck typing: no type casting needed — if an object has the method, it works regardless of declared type. Design note: frequent downcasting suggests a design smell — often indicates missing polymorphism. Consider adding a method to the base class or using the Visitor pattern.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last OOP Concepts project, I used this when...' immediately makes your answer more credible and memorable.