0

Im reading through someone else´s code and theres this piece of code:

class Wrapper {
        UnaryOperator<String> f;
    }
    Wrapper w = new Wrapper() { // line 3
        {
            f = s -> s.length() <= 1 ? s : f.apply(s.substring(1)) + s.substring(0, 1);
        }
    };

So if i understood it correctly, he creates a new Wrapper objecet and already initializes its variable f. I´m unfamiliar with the syntax from line 4 on, i only knew something like that from anonymous classes, but this isn´t one. Can you just initializes variables in between {} after you create a new Class()? Can you also do more than that, like override or define new methods? And why do you have to put {} in between each initialization?

J.Hurete
  • 31
  • 3
  • It **is** an anonymous class, containing an instance initializer block. This is really sloppy, though. The Wrapper class should have a better name, a constructor taking a UnaryOperator, name it correctly, and provide a getter, or even just a method delegating to the operator. Or it should simply not exist, because I don't see any value added by this class. – JB Nizet Mar 11 '18 at 10:29

1 Answers1

0

It is an Instance Initialization Block. Read more in this question

Orest Savchak
  • 4,529
  • 1
  • 18
  • 27