I recently went for a Java Interview where the interviewer asked me a question I could not answer. He asked me how I’d create a class whose instances can be assigned to a String, just like a string. Allow me to explain:
Say I create a class, MyClass and I create an object of it, say obj. The assignment should be such that:
MyClass obj = "my Text";
I searched for this sort of thing but could not get any precise answers.
You say “assigned to a String” but your code example shows being assigned a
Stringvalue. These are very different things. The former is easy: just write atoString()method inMyClass. The latter is basically impossible sinceStringis a final class.More technically with respect to the last point: If you look at the rules for assignment conversion, a
Stringvalue can only be assigned to a variable of typeStringor some wider reference type. The only wider reference types areObject,CharSequence,Serializable, andComparable<String>. (Tip of the hat to Stephen C).