An instance of the Java Java class cannot be passed to String. What for?

Why can instance A be used in List, but cannot pass it to String?

class A{} ... A a = new A(); List list = (List)a; //pass String s = (String)a; //compile error 
+5
source share
3 answers

The compiler, according to the specification, only considers the declared type a when it performs these checks for translations.

So you write:

 A a = new A(); 

But the compiler only takes into account

 A a; // = <something>; 

So, he knows that a cannot be a String , since a class can have only one superclass (without multiple inheritance), there cannot be a subclass of a , which is also a string.

But for interfaces, this is not true. Therefore, although we know that class a does not implement List , there may exist class B defined as follows:

 class B extends A implements List {} 

And since the compiler only considers the declared type, it must assume that you can also assign new B() a .

So, since subclass a can implement the List interface, the compiler cannot assume that casting to List always fails.

Of course, the order will be unsuccessful in practice, although at runtime. But not at compile time.

+6
source

JLS Quote:

This is a compile-time error if for any two classes ( not interfaces ) Vi and Vj, Vi is not a subclass of Vj or vice versa.

String and A are unrelated classes, so this is a compile-time error. List is an interface, so it does not cause the same error.

Please note that your statement

instance A can be transferred to a list

Not entirely correct: A cannot be assigned to a List ; it's just a run-time failure, not a compile-time failure.

+7
source

A class in Java can only be passed to one of its super types or to one of the interfaces in one of its super types.

In your case, class A not a subclass of String . Therefore, A cannot be attributed to String . In addition, String is the final class, so you cannot write a class A that can be added to String .

Java already recognizes the need to easily display classes as strings, especially for debugging / logging purposes. To satisfy this need, the Object class is supplied with the toString() method. Because all Java classes extend from the Object class, all Java classes contain an implementation of the toString() method.

It is important to remember that the existence of the toString() method does not mean that A is a string, but means that you can get a string from A that describes an instance of A somewhat. If you find that the description provided is not for your purposes, you can override the method A toString() to get a better description like

 @Override public String toString() { return "my better description"; } 

Since the override is written in Java, you can also include any variable or other element that could eventually turn into a String (which, since all objects have toString() , contains almost everything).

+1
source

Source: https://habr.com/ru/post/1241610/


All Articles