Multiple cast in java

Asked

Viewed 97 times

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.

  • https://answall.com/q/181591/132 - This helps you?

  • new (D) is not a valid syntax in Java. This will give a build error.

  • @Victorstafusa sorry I was the one who got it wrong and wanted to say new D()

  • @Articuno is already translated

  • @Rita what do you want to do? This casting is strange..

1 answer

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:

  1. new D() creates an object of the type D.

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

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

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

You are not signed in. Login or sign up in order to post.