Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Implicit Conversion in Java

Tags:

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?

like image 354
CodeCamper Avatar asked Apr 12 '14 21:04

CodeCamper


People also ask

What is implicit conversions in Java?

Implicit Type ConversionJava converts shorter data types to larger data types when they are assigned to the larger variable. For example, if you assign a short value to an int variable then Java does the work for you and converts the short value to an int and stores it in the int variable.

Does Java have implicit type conversion?

In Java, the IDE does not allow you to use implicit conversion when assigning a double value to an integer variable. This is called an errant condition and can cause data loss.

What is implicit conversion example?

In implicit typecasting, the conversion involves a smaller data type to the larger type size. For example, the byte datatype implicitly typecast into short, char, int, long, float, and double. The process of converting the lower data type to that of a higher data type is referred to as Widening.

How do you do implicit type conversion?

Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.


1 Answers

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.
like image 57
DwB Avatar answered Sep 28 '22 08:09

DwB