Search code examples
javastringcastingdowncastupcasting

String to Object typecasting - Difference


What is the difference between.

public class Test {

    public static void main(String args[]) {
        String toBeCast = "cast this string";
        A a = toBeCast; // error - Type mismatch: cannot convert from String to A
        Object object = toBeCast;
    }
}


public class A {

}

When we say every object extends Object class, why does A a = toBeCast; not allowed, but this Object object = toBeCast; works fine.


Solution

  • Remember that old saying from geometry class - "Every square is a rectangle, but not every rectangle is a square". Generalize that to: "Every square/parallelogram/rhombus is a polygon, but not every polygon is a square/parallelogram/rhombus".

    Here's what you're doing :

    String toBeCast = "cast this string" //this rhombus is a rhombus: cool!
    A a = toBeCast; //this parallelogram is that rhombus : WTF? that doesn't make sense!  
    Object object = toBeCast; //this polygon is that rhombus: cool!