String to Object typecasting - Difference

2019-07-31 23:04发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-07-31 23:15

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?

查看更多
地球回转人心会变
3楼-- · 2019-07-31 23:17

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! 
查看更多
叛逆
4楼-- · 2019-07-31 23:20
  OBJECT
  /    \
  A    String

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

查看更多
Rolldiameter
5楼-- · 2019-07-31 23:21

Because String is not a Sub Class of A

查看更多
做个烂人
6楼-- · 2019-07-31 23:40

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

查看更多
登录 后发表回答