3
JPanel panel = new JPanel() {
        public void setBackground(Color c) {
           Logger.global.info("setBackground: c=" + c);
           super.setBackground(c);
        }
    };

I only know I can do JPanel panel = new JPanel();

Why can someone do the above? What's the name for it?

aioobe
  • 413,195
  • 112
  • 811
  • 826
user705414
  • 20,472
  • 39
  • 112
  • 155

2 Answers2

7

It is called an anonymous class.

That code basically creates a subclass of JPanel "on the fly" without giving it a name (thus the term anonymous class) and instantiates it.

Related questions and links:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

It is an anonymous class that you extend and define additional methods or override existing ones.

Note that the same way you can extend interfaces or abstract classes.

mishadoff
  • 10,719
  • 2
  • 33
  • 55