Home  >  Article  >  Java  >  How to use anonymous inner classes in Java?

How to use anonymous inner classes in Java?

王林
王林forward
2023-05-07 13:13:081380browse

Concept

1. Anonymous inner classes are classes without names.

Format

new name(parameter)
{
   ......
}

Usage Note

2. Anonymous internal categories do not have access modifiers.

Anonymous internal classes must inherit abstract classes or implement interfaces.

There cannot be static members or methods in anonymous inner classes.

Anonymous inner classes have no structure methods because there is no class name.

Example

public class Button {
    public void click(final int params){
        //匿名内部类,实现的是ActionListener接口
        new ActionListener(){
            public void onAction(){
                System.out.println("click action..." + params);
            }
        }.onAction();
    }
    //匿名内部类必须继承或实现一个已有的接口
    public interface ActionListener{
        public void onAction();
    }
 
    public static void main(String[] args) {
        Button button=new Button();
        button.click();
    }
}

The above is the detailed content of How to use anonymous inner classes in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete