Java 匿名类

匿名类

匿名类使你的代码更简洁。它们使你能够同时声明和实例化一个类。它们类似于局部类,只是没有名字。如果只需要使用局部类一次,可以使用它们。

本节涵盖以下主题:

声明匿名类

局部类是类声明,而匿名类是表达式,这意味着在另一个表达式中定义类。下面的例子,HelloWorldAnonymousClasses,在本地变量frenchGreeting和spanishGreeting的初始化语句中使用匿名类,但在变量englishGreeting的初始化中使用本地类:

public class HelloWorldAnonymousClasses {
  
    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }
  
    public void sayHello() {
        
        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
                greetSomeone("world");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);
            }
        }
      
        HelloWorld englishGreeting = new EnglishGreeting();
        
        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };
        
        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
                greetSomeone("mundo");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);
            }
        };
        englishGreeting.greet();
        frenchGreeting.greetSomeone("Fred");
        spanishGreeting.greet();
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
            new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }            
}

匿名类的语法

如前所述,匿名类是一个表达式。匿名类表达式的语法类似于构造函数的调用,只不过在代码块中包含了类定义。

考虑一下法语greeting对象的实例化:

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };

匿名类表达式包含以下内容:

  • new 的操作符
  • 要实现的接口或要扩展的类的名称。在本例中,匿名类正在实现接口HelloWorld。
  • 包含构造函数参数的圆括号,就像普通的类实例创建表达式一样。注意:当你实现一个接口时,没有构造函数,所以你用了一对空的圆括号,就像这个例子一样。
  • 一个主体,它是一个类声明主体。更具体地说,在主体中,方法声明是允许的,而语句则不允许。

因为匿名类定义是一个表达式,所以它必须是语句的一部分。在本例中,匿名类表达式是实例化frenchGreeting对象的语句的一部分。(这解释了为什么在右括号后面有分号。)

访问外围作用域的局部变量,声明和访问匿名类的成员

与局部类一样,匿名类也可以捕获变量;它们对封闭作用域的局部变量具有相同的访问权限:

  • 匿名类可以访问其外围类的成员。
  • 匿名类不能访问其封闭作用域中没有声明为final或实际上为final的局部变量。
  • 与嵌套类一样,匿名类中的类型声明(比如变量)会遮蔽外围作用域中具有相同名称的任何其他声明。有关更多信息,请参阅阴影。

匿名类在其成员方面也有与局部类相同的限制:

  • 不能在匿名类中声明静态初始化器或成员接口。
  • 匿名类可以拥有静态成员,只要它们是常量变量。

注意,你可以在匿名类中声明以下内容:

  • 字段
  • 额外的方法(即使它们没有实现任何超类型的方法)
  • 实例初始化
  • 局部类

但是,不能在匿名类中声明构造函数。

匿名类的例子

匿名类通常用于图形用户界面(GUI)应用程序中。

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
 
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

在这个例子中,方法调用btn。setOnAction指定当你选择Say 'Hello World'按钮时会发生什么。这个方法需要一个类型为EventHandler的对象。EventHandler接口只包含一个方法handle。该示例使用匿名类表达式,而不是用新类来实现该方法。注意,这个表达式是传递给btn的参数。setOnAction方法。

因为EventHandler接口只包含一个方法,所以可以使用lambda表达式而不是匿名类表达式。有关更多信息,请参阅Lambda表达式一节。

匿名类非常适合实现包含两个或更多方法的接口。下面的JavaFX示例来自自定义UI控件一节。突出显示的代码创建一个只接受数值的文本字段。它通过重写从TextInputControl类继承的replaceText和replaceSelection方法,用一个匿名类重新定义TextField类的默认实现。

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class CustomTextFieldSample extends Application {
    
    final static Label label = new Label();
 
    @Override
    public void start(Stage stage) {
        Group root = new Group();
        Scene scene = new Scene(root, 300, 150);
        stage.setScene(scene);
        stage.setTitle("Text Field Sample");
 
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10, 10, 10, 10));
        grid.setVgap(5);
        grid.setHgap(5);
 
        scene.setRoot(grid);
        final Label dollar = new Label("$");
        GridPane.setConstraints(dollar, 0, 0);
        grid.getChildren().add(dollar);
        
        final TextField sum = new TextField() {
            @Override
            public void replaceText(int start, int end, String text) {
                if (!text.matches("[a-z, A-Z]")) {
                    super.replaceText(start, end, text);                     
                }
                label.setText("Enter a numeric value");
            }
 
            @Override
            public void replaceSelection(String text) {
                if (!text.matches("[a-z, A-Z]")) {
                    super.replaceSelection(text);
                }
            }
        };
 
        sum.setPromptText("Enter the total");
        sum.setPrefColumnCount(10);
        GridPane.setConstraints(sum, 1, 0);
        grid.getChildren().add(sum);
        
        Button submit = new Button("Submit");
        GridPane.setConstraints(submit, 2, 0);
        grid.getChildren().add(submit);
        
        submit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                label.setText(null);
            }
        });
        
        GridPane.setConstraints(label, 0, 1);
        GridPane.setColumnSpan(label, 3);
        grid.getChildren().add(label);
        
        scene.setRoot(grid);
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值