How To Make My Own Way To Create An Object?

Nishant Chatterjee KMS :

Objects like Integer, String, T[] all have their own unique constructor call. For example, when creating an Integer, instead of putting Integer i = new Integer(5), you can instead put Integer i = 5. Same for String and arrays. I want to know if I could make my own unique replacement for constructor calls. I have a class called Fraction, where you put a numerator and denominator, and it can do whatever a fraction can do. Right now, this is how I construct it: Fraction f = new Fraction(3, 4), where the numerator is the first argument and the denominator is the second. I'm wondering if I could do something like Fraction f = 3/4, where I don't have to call the constructor. Thanks!

Tom Hawtin - tackline :

You can't add your own literals. The best you could do is a function that parses a literal string.

Fraction f = fraction("3/4");

3/4 will always be the compile-time constant int 0.

Guess you like

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