java override during object creation

karl picture karl · Oct 1, 2009 · Viewed 9.1k times · Source

in the following java code a JButton is created but at the same time one of its methods gets overridden. Qestion: is there a name for overriding in this way while creating the object?

the code:

   JButton myButton;
   myButton = new JButton ("ok"){

        @Override
        public void setText(String text) {
            super.setText(text +", delete");
        }

the jbutton's label is now "ok, delete"

Answer

Brian Agnew picture Brian Agnew · Oct 1, 2009

That's an anonymous class. From Java in a Nutshell

An anonymous class is a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator. While a local class definition is a statement in a block of Java code, an anonymous class definition is an expression, which means that it can be included as part of a larger expression, such as a method call. When a local class is used only once, consider using anonymous class syntax, which places the definition and use of the class in exactly the same place.

It's a common means of providing a specialisation of a base class without explicitly defining a new class via the class expression.