[英]Different ways to create classes?
I've been practicing making GUI in netbeans and came across this auto generated code 我一直在练习在netbeans中制作GUI,并遇到了这个自动生成的代码
saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
saveButtonMousePressed(evt);
}
I'm just confused in the argument "new java.awt.event.MouseAdapter()". 我只是对参数“ new java.awt.event.MouseAdapter()”感到困惑。 I know that when we use the "new" keyword we make an object of that class. 我知道,当我们使用“ new”关键字时,我们将创建该类的对象。 But after that "new" statement it declared a method so my perception was that "an object with a method? I know we create object so that we can use methods not create a method within them". 但是在“ new”语句之后,它声明了一个方法,所以我的感觉是“一个带有方法的对象?我知道我们创建了对象,因此我们可以使用方法而不在其中创建方法”。
After researching and reading about Inner Classes, I now have a different perspective. 在研究和阅读了有关内部类的知识之后,我现在有了不同的看法。
Would that be possible to create a class in a argument with the "new" statement? 使用“ new”语句在参数中创建类是否可行? if true then that code didn't created a object, but instead created a class. 如果为true,则该代码未创建对象,而是创建了一个类。
If my conclusion would be right there are 2 ways (I know so far) to create classes in java. 如果我的结论是正确的,那么有两种方法(到目前为止我知道)可以在Java中创建类。
by using, 通过使用,
public clas Sample() { //insert methods here }
and by using, 并通过使用,
public void getSomething(new Sample() { //insert method here })
Did I get this one right? 我说对了吗? I'm just a beginner in java(Self Study). 我只是java(自学)的初学者。
It's not a different way to create a class
, actually you define it in the same way you would with any other class but you don't name it, it is just a specialized MouseAdapter
. 创建class
并不是一种不同的方式,实际上,您可以使用与其他任何类相同的方式来定义它,但是您没有为其命名,它只是一个专用的MouseAdapter
。
What actually happens is that you define a specialized version of mousePressed
without the need to associate it to a named subclass of MouseAdapter
. 实际发生的情况是,您定义了mousePressed
的专用版本,而无需将其与MouseAdapter
的命名子类相关联。 It's like defining and using the class in the same point. 就像在同一点定义和使用类一样。 You define a specific class with specific behavior and instantiate it. 您定义具有特定行为的特定类并实例化它。
Indeed that's called an anonymous class . 实际上,这被称为匿名类 。 This has nothing in common with an inner class , which is a class that is defined inside another class (so they are nested). 这与内部类没有什么共同之处, 内部类是在另一个类内部定义的一个类(因此它们是嵌套的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.