Java 中的自定义隐式转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23036546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:12:10  来源:igfitidea点击:

Custom Implicit Conversion in Java

java

提问by CodeCamper

In C# I can create my own implicit conversion for my classes as follows...

在 C# 中,我可以为我的类创建自己的隐式转换,如下所示...

public static implicit operator TypeYouWantToChangeTo (ClassYouAreChanging c)  
{ 
    TypeYouWantToChangeTo x;
    //convert c to x
    return x;
}

How do you make a class be able to implicitly convert to another class? Also in C# I can change implicit to explicit to also create the ability to cast manually. How do you accomplish this in Java?

你如何让一个类能够隐式转换为另一个类?同样在 C# 中,我可以将隐式更改为显式,以创建手动转换的能力。你如何在 Java 中实现这一点?

采纳答案by DwB

You can not overload operators with Java. Add a method to your class of choice to perform the conversion. For example:

你不能用 Java 重载运算符。向您选择的类添加一个方法来执行转换。例如:

public class Blammy
{
    public static final Blammy blammyFromHooty(final Hooty hoot)
    {
        Blammy returnValue;

        // convert from Hooty to Blammy.

        return returnValue;
    }
}

Edit

编辑

  • Only built-in types have implicit conversions.
  • Explicit conversion (in java) is called a cast. for example, int q = 15; double x = (double) q;
  • There can never be implicit conversions of your custom types.
  • extendsand implementsare not conversion.
  • All implicit conversions are for primitive types.
  • 只有内置类型具有隐式转换。
  • 显式转换(在 Java 中)称为强制转换。例如,int q = 15; double x = (double) q;
  • 您的自定义类型永远不会有隐式转换。
  • extends并且implements不是转换。
  • 所有隐式转换都是针对原始类型的。