Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How to cast between objects? How about interfaces?

Cast interfaces objects
0
Posted

How to cast between objects? How about interfaces?

0

• Upper cast from subclass to supercalss, no need to cast, since the ISA relationship. OakTree is a Tree. • Down cast from superclass to subclass, an explicit cast is needed to avoid compile time error. If you cast Tree to OakTree, it would possibly be right, but not necessarily, since this particular Tree actually might be an AppleTree. In that case, a ClassCastException will be thrown out at the run time • If you cast between siblings or even irrelevant classes, a compile time error results, since compiler has the type information of them. for example, if you cast a OakTree to an AppleTree, or even a Furniture, compile will error out. • However, there is a catch, if you cast to an interface, even they are irrelevant, and compiler might let you go without an error.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123