定义Java中的类型转换

安德森·格林(Anderson Green):

我想在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+"");
    }
}
戴夫:

您不能进行转换,但是可以提供转换功能:

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

然后,酒吧变成:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章