String to Object typecasting - Difference

回眸只為那壹抹淺笑 提交于 2019-12-11 04:48:52

问题


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.


回答1:


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! 



回答2:


  OBJECT
  /    \
  A    String

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




回答3:


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




回答4:


Because String is not a Sub Class of A




回答5:


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?



来源:https://stackoverflow.com/questions/27052943/string-to-object-typecasting-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!