Robert Lewis
Robert Lewis

Reputation: 1907

override toString() method in class Optional

I have an instance variable defined as:

final Optional<myClass> myOptional; 

I would like to override its toString() method so that instead of returning "[Optional(the value)]" it simply returns "(the value)" (or something else if it's empty). But I can't create a subclass of Optional since it is apparently final. How can I do this?

Upvotes: 3

Views: 2747

Answers (2)

Stuart Marks
Stuart Marks

Reputation: 132490

GhostCat is correct in that you cannot subclass Optional and override its toString method. However, you can probably get the effect you want by writing this:

String myString = myOptional.map(MyClass::toString).orElse("(empty)")

This sets myString to the result of the value's toString method if a value is present, otherwise it substitutes the string (empty) if the value is absent. Of course, you can put whatever substitute string you want there.

Optional is final so that it will be easier to convert into a value type in a future version of Java. See Project Valhalla for information about value types, in particular State of the Values for an overview and background.

Optional is also intended to be immutable, so subclassing must be prevented. See Bloch, Effective Java, Item 15.

Upvotes: 5

GhostCat
GhostCat

Reputation: 140573

You can't.

There is no way of changing the behavior of methods of a class from outside its source code. So, the only choices you got are:

  1. Turn to the source code of that class and make changes there
  2. Extend the class, override the method and then use objects of the derived class

In your case, both options not possible. Sorry, end of story.

(yes, other, interpreted languages would allow you to do so; but Java does not).

Upvotes: 2

Related Questions