创建类的不同方法?

Different ways to create classes?

我一直在练习在 netbeans 中制作 GUI 并遇到了这个自动生成的代码

  saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                saveButtonMousePressed(evt);
            }

我只是对这个论点感到困惑 "new java.awt.event.MouseAdapter()"。我知道当我们使用 "new" 关键字时,我们创建了 class 的对象。但是在那 "new" 声明之后它声明了一个方法所以我的看法是 "an object with a method? I know we create object so that we can use methods not create a method within them".

在研究和阅读有关 Inner 类 之后,我现在有了不同的看法。

是否可以在带有 "new" 语句的参数中创建一个 class?如果为真,则该代码没有创建对象,而是创建了一个 class.

如果我的结论是正确的,有 2 种方法(到目前为止我知道)可以在 java.

中创建 classes
  1. 通过使用,

    public clas Sample() {
    
    //insert methods here
    
    }
    
  2. 并通过使用,

    public void getSomething(new Sample() { //insert method here })
    

我答对了吗?我只是 java(自学)的初学者。

创建 class 的方式并没有什么不同,实际上您可以像定义任何其他 class 一样定义它,但您没有给它命名,它只是一个专门的MouseAdapter.

实际发生的是,您定义了 mousePressed 的专用版本,而无需将其关联到 MouseAdapter 的命名子 class。这就像在同一点定义和使用 class 一样。您定义具有特定行为的特定 class 并将其实例化。

确实这叫做 anonymous class. This has nothing in common with an inner class,它是在另一个 class 中定义的 class(因此它们是嵌套的)。