0
public class TypeConversion {
    Human human = new Human();
    NonHuman nonHuman = new NonHuman();
    
    public void test()
    {
        nonHuman = (NonHuman) human; //Cannot cast from Human to NonHuman
    }
}

class Human { }
class NonHuman {}

I was expecting the type conversion to work as its explicit, atleast at compile-time. And result in to a ClassCastException or some thing similar at run-time.

So, I am interested to know what are the restrictions around type conversion at compile time.

samshers
  • 1
  • 6
  • 37
  • 84

1 Answers1

1

Random classes cannot be typecastes/converted to each other.

Two types of conversions are usually allowed Conversion of a sub class object into a superclass variable (Implicitely) Conversion of a superclass object into a sub-class variable (Explicitely)

So your case would work only if the two classes had a parent child or a child parent relationship.

Ragesh G R
  • 39
  • 8