Java中的自动类型转换? [英] Automatic type conversion in Java?

查看:131
本文介绍了Java中的自动类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Java中进行自动隐式类型转换?例如,假设我有两种类型,"FooSet"和"BarSet",它们都是Set的表示形式.在类型之间进行转换很容易,因此我编写了两个实用程序方法:

Is there a way to do automatic implicit type conversion in Java? For example, say I have two types, 'FooSet' and 'BarSet' which both are representations of a Set. It is easy to convert between the types, such that I have written two utility methods:

/** Given a BarSet, returns a FooSet */
public FooSet barTOfoo(BarSet input) { /* ... */ }

/** Given a FooSet, returns a BarSet */
public BarSet fooTObar(FooSet input) { /* ... */ }

现在说有一种我想调用的方法:

Now say there's a method like this that I want to call:

public void doSomething(FooSet data) {
    /* .. */
}

但是我只有一个BarSet myBarSet ...这意味着需要额外输入,例如:

But all I have is a BarSet myBarSet...it means extra typing, like:

doSomething(barTOfoo(myBarSet));

是否可以告诉编译器某些类型可以自动转换为其他类型?我知道在C ++中有重载是可能的,但是我在Java中找不到方法.我只想输入:

Is there a way to tell the compiler that certain types can automatically be cast to other types? I know this is possible in C++ with overloading, but I can't find a way in Java. I want to just be able to type:

doSomething(myBarSet);

编译器知道会自动调用barTOfoo()

And the compiler knows to automatically call barTOfoo()

推荐答案

答案很简短:C ++中的重载是可能的,但Java中没有办法做到这一点.

The answer is short: It's possible with overloading in C++ but there is no way to do that in Java.

这篇关于Java中的自动类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆