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

How to use anonymous inner classes in Java?

王林
Release: 2023-05-07 13:13:08
forward
1434 people have browsed it

Concept

1. Anonymous inner classes are classes without names.

Format

new name(parameter)
{
   ......
}
Copy after login

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();
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template