2

I want to override toString() method of class LocalDate. I know how to override toString() method of class with public constructor like java.util.Date using code like this:

Date date = new Date () {
   @override
   public String toString() {...}
}

But i cant do the same thing with class that have private constructor like java.time.LocalDate Is there are any way how i can workaround this?

A_Gubar
  • 23
  • 2
  • 3
    No, you can’t do that. The `LocalDate` class is final, meaning you cannot create any subclass. It’s also the wrong way of obtaining what you want. To format a `LocalDate` into the string of your liking use an appropriate `DateTimeFormatter`. – Ole V.V. Nov 14 '18 at 14:55
  • Possibly related: [Localdate.format, format is not applied](https://stackoverflow.com/questions/50462041/localdate-format-format-is-not-applied) – Ole V.V. Nov 14 '18 at 14:58
  • I appreciate the comeback! – GhostCat Nov 18 '18 at 18:19

2 Answers2

3

The simple answer is: you can't.

That class javadoc tells you:

public final class LocalDate

You can't extend a final class, therefore you can't change the behavior of any of its methods, at least not in Java. (Kotlin offers extension methods, that allow you to do "sort of" that thing).

But as pointed out in the comments, assuming that your problem is to properly format a Date, LocalDate, ... instance, then overriding toString() is simply the wrong approach. You turn date objects into formatted date strings by using a DateFormatter, see here for guidance.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

We cannot override methods of a final class.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Karthik P
  • 53
  • 1
  • 8