How to initialize anonymous inner class in Java

后端 未结 4 1556
庸人自扰
庸人自扰 2021-01-08 00:24

Is there any way to initialize anonymous inner class in Java?

For example:

new AbstractAction() {
    actionPerformed(ActionEvent event) {
    ...
          


        
相关标签:
4条回答
  • 2021-01-08 01:00

    Use an Initializer Block:

    new AbstractAction() {
    
        {
            // do stuff here
        }
    
        public void actionPerformed(ActionEvent event) {
        ...
        }
    }
    

    Initializing Instance Members

    Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

    {
        // whatever code is needed for initialization goes here
    }
    

    The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

    Source:

    • Java Tutorial > Initializing Fields
    0 讨论(0)
  • 2021-01-08 01:01

    You can use the instance initialization section:

    new AbstractAction() {
        {
           //initialization code goes here
        }
    
        actionPerformed(ActionEvent event) {
        ...
        }
    }
    
    0 讨论(0)
  • 2021-01-08 01:03

    Or you can just access the variables of the outer class from the inner class.

    http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes#Anonymous_Classes

    0 讨论(0)
  • 2021-01-08 01:21

    It's not quite clear what you mean, but you can use an initializer block to execute code at construction time:

    new AbstractAction() {
    
        {
            // This code is called on construction
        }
    
        @Override public void actionPerformed(ActionEvent event) {
        ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题