Upcasting and Downcasting

Asked

Viewed 260 times

1

I know that Upcasting is to convert a subclass object to the superclass and Downcasting is to convert a superclass object to the subclass.

But in relation to the loss of values and the like, as it turns out?

Example: We have the superclass Carro and the subclass CarroMelhorado.

CarroMelhorado is a Car, but with more things. But if I speak Carro c1 = new CarroMelhorado(); from now on that C1 gains new attributes and methods that can be used ?

And in another case: CarroMelhorado cm1 = new Carro() here would be a Downcasting, only cm1 of the type CarroMelhorado has more than Carro doesn’t have, at all CarroMelhorado being a Carro, with that assignment cm1 would lose all their stuff "the most"?

  • The examples given are not about up or downcasting. I recommend reading the following link to better understand the concepts: What is upcasting and downcasting in the Java language?

  • Only a constructive criticism: the word "lose" is not a noun. The correct one would be "loss".

  • All right, and what would be a real application of this and for what purpose ? I am layman in the subject, I wanted to understand in practice and theory, in the course I am doing explains Upcasting and Downcasting superficially, I visualize better with real examples.

1 answer

1


This case you’re saying you do downcasting It doesn’t even compile so it’s doing nothing, at least nothing valid. Something more general can not become more specialized precisely because it does not have everything that is necessary.

I wouldn’t call it casting something that exists only in the variable declaration through a constructor. The casting, implicit or explicit, it would occur if an existing object were placed in a variable of another type. There is no casting can’t talk about loss.

Castings which involve loss should not be allowed implicitly, and in some cases nor explicitly. In other more powerful languages it is possible to establish own rules for casting for each object, but not the case for Java.

The question is not about casting.

This is partly explained in What is upcasting and downcasting in the Java language?.

What you call an attribute is actually a field.

  • It even compiles, but everything the subclass has specific is no longer visible on that object.

  • I referred to the second example, of course, the first does not even compile.

  • The second does not compile: https://ideone.com/tdal5F, the first is quite usual.

  • Really, I made confused with the classes cited in the question.

Browser other questions tagged

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