CodeCamper
CodeCamper

Reputation: 6980

Custom Implicit Conversion in Java

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

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?

Upvotes: 19

Views: 22837

Answers (1)

DwB
DwB

Reputation: 38300

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

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.
  • extends and implements are not conversion.
  • All implicit conversions are for primitive types.

Upvotes: 26

Related Questions