Can Java draw something?

At school, I studied for the java course, and my understanding of casting is rather limited.

The type of fill I understand is to merge int into double. It makes sense; 1 will become 1.0

The type of casting that I don’t quite understand is as follows: casting a custom object (say superRectangle) to another client object (for example, myRectangle). (this assumes that it myRectangleis a subclass superRectangle) What happens to all private or public fields associated with an instance superRectangle? How does the program know this is a legal move? For all that matters, I could just type int in a string, and what does that mean anyway?

+4
source share
3 answers

Strictly speaking, the transition from intto is doublenot performed, but the conversion. Casting is a reinterpretation of the same unchanged bit pattern in memory belonging to a different type. And this is exactly what distinguishes reference types in Java before: you have an object of a specific, immutable type, and you just look at it as an instance of one of its supertypes.

You will not be allowed to use Integerfor String, because the latter is not the former supertype. This is provided at compile time and double checked at runtime.

+6
source

, , .

Integer Double siblings, ,

Double d = (Double)(new Integer(4));// compile time error

.

:

+2

, "superRectangle" "myRectangle", . , .

, MyRectangle YourRectangle SuperRectangle...

:

SuperRectangle superRect = new MyRectangle();
MyRectangle castedMyRect = (MyRectangle)superRect;

ClassCastException:

SuperRectangle superRect = new MyRectangle();
YourRectangle castedYourRect = (YourRectangle)superRect;
+1

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


All Articles