在Java中定义类型转换

And*_*een 7 java types casting

我想在Java中定义从任意类型到基本数据类型的类型转换.是否可以定义从一个任意类型到另一个任意类型的转换?

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+"");
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ave 9

你不能投,但你可以提供转换功能:

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

酒吧然后变成:

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