简体   繁体   中英

Defining a type cast in Java

I want to define a type cast from an arbitrary type to a primitive data type in Java. Is it possible to define a cast from one arbitrary type to another arbitrary type?

public class Foo{
    //methods, constructor etc for this class
    ...
    //make it possible to cast an object of type Foo to an integer 
}
//example of how an object of type foo would be cast to an integer
public class Bar(){
    public static void main(String[] args){
        Foo foo1 = new Foo();
        int int1 = (int)foo1;
        System.out.println(int1+"");
    }
}

You can't cast it, but you can provide a conversion function:

public class Foo{
    //methods, constructor etc for this class
    ...
    public int toInt(){
        //convert to an int.
    }    
}

Bar then becomes:

public class Bar(){
    public static void main(String[] args){
        Foo foo1 = new Foo();
        int int1 = foo1.toInt();
        System.out.println(int1+"");
    }
}

It is not possible to convert from a class type (eg. Foo) to a primitive type directly. Instead you should define methods (eg. int asInteger() ) that return the value of a Foo object as an integer.

No, it's not. It wouldn't really make sense: how could a Foo become an int ?

Rather define a sequence of appropriate methods, such as:

public int toInt() { return 42; }

Typecasting between primitive types and Java types, such as between int and Integer , was not even originally part of Java.

class Foo must extend Number. Why would you want to do that though? why not just access an int variable inside of foo.

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