Up Casting in Java
Up Casting is the process of assigning a subclass object to a superclass reference or a super-interface reference.
Key Points
- Up casting is also known as implicit casting.
- It is performed automatically by the compiler.
- In up casting, the compiler treats the subclass object as a superclass object.
- No explicit cast is required.
Parent p = new Child(); // Up casting
Accessing Members During Up Casting
- When up casting occurs, the programmer can access only the members of the superclass using the superclass reference.
- Subclass-specific members cannot be accessed directly.
System.out.println("Parent method");
class Child extends Parent {
System.out.println("Child method");
// p.display(); // Not allowed
Up Casting with Method Overriding
- If method overriding is present:
✓The overridden method of the subclass is executed.
✓This is due to runtime polymorphism (dynamic method dispatch).
System.out.println("Parent running");
class Child extends Parent {
System.out.println("Child running");
p.run(); // Output: Child running
👉 Here, the method call depends on the object, not the reference.
Why Up Casting Is Important
- Required to achieve runtime polymorphism.
- Helps in writing flexible and loosely coupled code.
- Widely used in method arguments, collections, and frameworks.
Important Correction
❌ Up casting is required to achieve runtime error → Incorrect
✅ Up casting is required to achieve runtime polymorphism → Correct
Comments
Post a Comment