How to write custom casting method in Java

orezvani :

I have a Java class that has a few members. I want to write a custom cast for it. I was wondering how is it possible to do so?

Let's assume the class is as follows:

class Person {
   private int age;
   private float weight;

   // getters and setters and etc
}

I would like the int cast to return the member age of an object, and the float cast to return the weight of an object.

For instance:

public class Main {
    public static void main(String[] args) {

        // create an object
        Person P = new Person();
        P.setAge(21);
        P.setWeight(88.0);

        // case 1: casting object to an existing data type
        int personAge = (int) P; // would return the age
        float personWeight = (float) P;  // would return the weight

        // case 2: casting an existing data type to an object
        Person P2 = (Person) personAge; // this would create an instance of the object whose age is assigned and weight is not assigned

    }
}

I was wondering if it is possible to do the opposite. In particular, casting int to Person would return an instance of Person that its age is assigned and similarly for float.

I know this question may not have an answer. But because I did not find any useful results in my search, I decided to ask it.

P.S. I understand that for a String, the toString method would take care of case 1.

Andrew Tobilko :

You can't overload the cast operator. Java doesn't support it and probably never will.

To convert a single value to an instance of the desired class, we use static factory methods.

public static Person fromAge(int age) {
    return new Person(age);
}

They often return a partially constructed object. In the snippet above, a newly constructed person has only age set: other fields will have their default values.

To do the opposite, we use getters.

public int getAge() {
    return age;
}

However, since toString is already there, it makes sense to add other data types as well.

toInt makes no sense when it's applied to me (as an instance of the Person class). It could be my height, my weight, my age, a number of times I went to a bathroom today, etc. I can't represent myself by one int number, neither can a large majority of classes.

On the other hand, toString can do this job pretty well: I can give you (read return) a summary of my hobbies, my biometric information, even my picture. Or I can leave it to the default implementation, which still would satisfactorily represent an object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92484&siteId=1