简体   繁体   中英

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.

Consider the following class hierarchy.

public class Mammal

And a few subclasses..

public class Dog extends Mammal
public class Cat extends Mammal

Essentially, what you want to do, is to take a Dog, and make it a Cat. Clearly a dog is not a Cat, thus this cast can not ever work.

A dog is a mammal, though. This cast is fine. Cat is a mammal too, so this cast is fine too. But cat can never be a dog, nor can dog ever be a cat.

What you can do, is to create a constructor for ScalarFloat that would take an instance of ScalarInt and build an instance of ScalarFloat from that, conversion this way would not incur a loss of precision. But converting from a float to an int would incur a loss of precision, thus this is something you might not want to do..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM