Anonymous Inner Class Constructors

Have been writing anonymous inner class for many years, when I suddenly hit a question today while writing a quick dirty test class. I needed to initialize stuff within the anon inner class, but how?

Found this link to teach me how to do that — just by using braces { }.

Musings of Laurie

Solved my problem, but had me thinking. I can’t call super() to call the parent constructor, what if I do not want to override the default constructor? After an hour of thinking, I realized the answer was right there too. To declare the anon inner class I have already specified which constructor to call before the declaration of the anon inner class, like this:


// i'm calling the JButton(String) constructor
new JButton("asd") {
  {
    // override constructor
  }
};

Certification doesn’t mean you know and remember everything!

The comment form is closed.