1
I’m having a hard time doing an exercise because I don’t know how to solve this kind of casting:
The class D
is the superclass.
The class C
is the subclass.
D d = (D) (C) new D();
I’d be grateful if someone could help me.
1
I’m having a hard time doing an exercise because I don’t know how to solve this kind of casting:
The class D
is the superclass.
The class C
is the subclass.
D d = (D) (C) new D();
I’d be grateful if someone could help me.
0
Let’s assume we have this code:
public class C {}
public class D extends C {}
That is, all that is a D
, is also a C
. But the opposite is not necessarily true.
And then this:
D d = (D) (C) new D();
Which is a concise way of writing what can be interpreted with these four steps:
D temp1 = new D(); // Etapa 1
C temp2 = (C) temp1; // Etapa 2
D temp3 = (D) temp2; // Etapa 3
D d = temp3; // Etapa 4
What each step does:
new D()
creates an object of the type D
.
The cast for C
checks if the object is of the type C
. How does the compiler know that all D
is a C
, then this cast is valid. The resulting subexpression is of the type C
.
The cast for D
checks if the object is of the type C
. How does the compiler know that not all C
is a D
, then a check will be done at runtime. If the object of type C
is not a D
, one ClassCastException
will be launched. In this case, this check will always be successful. The resulting subexpression is of the type D
.
The resulting value is assigned to the variable d
. How does the compiler know what is right on the sign of =
is the type D
and the variable d
is also the type D
, then this assignment is valid.
Note that there are two types of Casts here. One of them (that of step 2) is a upcasting and the other (that of stage 3) is a downcasting. See more about this in that other question.
Victor very grateful for the clarification, it helped me a lot
@Rita In this case, if you have no further doubt about this question, click on what appears below the voting number of this answer to mark it as accepted and mark your question as resolved. It was a pleasure to help you.
Browser other questions tagged java cast
You are not signed in. Login or sign up in order to post.
https://answall.com/q/181591/132 - This helps you?
– Victor Stafusa
new (D)
is not a valid syntax in Java. This will give a build error.– Victor Stafusa
@Victorstafusa sorry I was the one who got it wrong and wanted to say new D()
– Rita
@Articuno is already translated
– Rita
@Rita what do you want to do? This casting is strange..
– Marlysson