Похожие чаты

Regarding upcasting and downcasting in java im trying to come

up with some examples & causes of different kinds of errors regarding casting and polymorphism

given B extends A

((B) new A())
will cause a runtime error, right?

and say C doesn't extend anything
(C(new A()))
B ba = new A()
will cause a compile time error


so
are there any more cases like this im not thinking about that would result in compile/runtime errors?

also if u can provide an intuition behind those that'd be appreciated thanks

7 ответов

23 просмотра

A casted to B is just regular downcasting. It won't cause an error

dankey- Автор вопроса

isn't there a scenerio in which this'll cause an error?

dankey
isn't there a scenerio in which this'll cause an e...

If B didn't extend A Java would've thrown a ClassCastException which is a RuntimeException

dankey- Автор вопроса
Nader Jafari
If B didn't extend A Java would've thrown a ClassC...

i was sure im missing something. sure there aren't any small annoyances regarding casting in between classes with is a relation between them?

dankey
i was sure im missing something. sure there aren'...

I don't think so. Primitives are all numeral types so it's just a matter of widening and narrowing. As for references, classes with parent-(grand)child relations can be casted, you lose fields and methods upcasting but since children can't make inherited fields and methods less visible it just can't go wrong. The only slightly problematic one is downcasting which you can prevent at compile time using instanceof

dankey- Автор вопроса
Nader Jafari
I don't think so. Primitives are all numeral types...

umm can you give an example for such problematic downcasting?

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта