Search code examples
javatypecasting-operator

Custom type casting in Java


In Java, I have a class ScalarNumber and two classes ScalarInt and ScalarFloat that derive from ScalarNumber. However, when I try casting between the two, I get an error that says, usemathobject.ScalarInt cannot be cast to usemathobject.ScalarFloat.

Is it possible to define a way to convert one class into another class when they both derive from the same class?

While I was searching I found some people who wanted to cast a class to a primitive type, and others said that this was not possible, but I want to convert one class into another class. I did find out how to do it in C# by defining a function like public static explicit operator ScalarFloat(ScalarInt a) but I could not find the Java equivalent. I am using Netbeans IDE 6.9.1 on Windows Vista.


Solution

  • short answer: NO, ScalarInt and ScalarFloat objects cannot be cast to each other..

    You can however cast both these objects to ScalarNumber and use common properties defined in that class as a workaround