Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Initialization Block

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;
            }
        };**
like image 483
EdgeCase Avatar asked Mar 22 '26 03:03

EdgeCase


2 Answers

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.

like image 112
Heisenbug Avatar answered Mar 23 '26 17:03

Heisenbug


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);
like image 24
TotoroTotoro Avatar answered Mar 23 '26 17:03

TotoroTotoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!