String to Object typecasting - Difference

549 views Asked by At

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.

5

There are 5 answers

1
drew moore On BEST ANSWER

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! 
0
Sail On

Take a view at an object window and an object screw. Both of them are Objects, but they are more as an object. There have more specifications to describe both so you know what is a window or a screw. The same is in objects in coding language Java. A casting of classes from whole different environment makes non sense.

String is also Final and an immutable object. Please take a look at Why is String final in Java?

1
shazin On

Because String is not a Sub Class of A

0
Ker p pag On
  OBJECT
  /    \
  A    String

this is how your class hierarchy looks like that is why casting to Object A gives an error.

0
Fehr On

The variable toBeCast is an instance of the string struct. The variable a is an instance of the class A.

Its possible to compile the following:

String toBeCast = "cast this string";
Object obj = toBeCast;

This is because, as you say every instance of an object (including strings) inherit from System.Object, however the following will not compile:

A a = toBeCast;

Although a (Type A) inherits from System.Object and toBeCast (Type String) inherits from Object, Type A does not inherit from Type String.

And so the compiler returns: "Type mismatch: cannot convert from String to A".