Posts

Showing posts with the label Java Type Casting

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 Per...

Up Casting in Java: Definition, Rules, and Examples

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. class Parent {     void show() {         System.out.println("Parent method");     } } class Child extends Parent {     void display() {         System.out.println("Child method");     } } Parent p = new Child(); p.show(); // Allowed // p.display(); // Not allowed Up Casting with Method Overriding If method overriding is...