3

Can someone help me understand the following construct? I am having trouble understanding if this is an initializer or an anonymous class. I am not familiar with this syntax.

   JTable jt = new JTable(data, fields) **{
            public TableCellRenderer getCellRenderer(int row, int column) {
                // TODO Auto-generated method stub
                return renderer;
            }
        };**
mKorbel
  • 109,525
  • 20
  • 134
  • 319
EdgeCase
  • 4,719
  • 16
  • 45
  • 73
  • Possible duplicate - http://stackoverflow.com/questions/6432545/is-this-a-variation-of-an-anonymous-inner-class – mre Sep 02 '11 at 20:09

2 Answers2

6

It creates an anonymous inner class which extends JTable, and overrides getCellRenderer method.

Long explanation:

your are creating a class that extends JTable without explicitly assign it a name instead of using standard class declaration:

public class ExtendedJTable extends JTable{}

The visibility of this class is limited to the class inside which it is defined and instantiated. It's quite useful for example when you need, like in the code you posted, to override a method (getCellRenderer()) of a particular class (JTable), for some purposes limited to the current class context.

This approach has some benefits and also some limitations. For a deeper discussion have a look at this article.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
2

You're doing 2 things here:

  • create an object of a class that extends JTable. This is an anonymous class because it's not declared separately anywhere else.
  • In this class, you override the JTable's method getCellRenderer(int row, int column);
TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76