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 String value. These are very different things. The former is easy: just write a toString() method in MyClass. The latter is basically impossible since String is a final class.
More technically with respect to the last point: If you look at the rules for assignment conversion, a String value can only be assigned to a variable of type String or some wider reference type. The only wider reference types are Object, CharSequence, Serializable, and Comparable<String>. (Tip of the hat to Stephen C).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With