我试图学习如何在 Java 中执行 lambda 表达式,但我却感到困惑。所以我对匿名类的理解是这样的:
public class SomeObject {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(new SomeObject());
}
}
我之前看到过匿名内部类这个词,但当时我并不知道什么是常规的匿名类。我看到的很多线程和视频似乎都将匿名内部类称为“匿名类”。它们是同义词吗?我对匿名内部类的理解是:
public class Rectangle {
private double length;
private double width;
private double perimeter;
public void calculatePerimeter() {
perimeter = (2*length) +(2*width);
}
public static void main(String[] args) {
Rectangle square = new Rectangle() {
public void calculatePerimeter() {
perimeter = 4*length;
}
};
}
}
所以本质上,我不必为 Square 编写一个子类,然后重写calculatePerimeter() 方法,我可以创建一个一次性的 Square 类,然后重写它们中的方法。它是否正确?
因此,匿名内部类与继承有关。但我不明白它的用途。也许,这是因为我以前从未使用过它们,或者因为我没有太多的编程经验。你能给我举个例子或者解释一下它什么时候有用吗?
更新:当我将匿名内部类的代码移至 IDE 时,我发现存在错误;显然,“正方形”甚至没有继承矩形的字段。这不是更没用了吗?
等价的是:
public class Rectangle {
private double length;
private double width;
private double perimeter;
public void calculatePerimeter() {
perimeter = (2*length) +(2*width);
}
}
public class Square extends Rectangle {
@Override
public void calculatePerimeter() {
perimeter = 4*getLength();
}
public double getLength() {
return length;
}
}
最佳答案
So my understanding of an anonymous class is this:
public class SomeObject {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(new SomeObject());
}
}
那里没有匿名类。 SomeObject
类有一个名称……因此它不是匿名的。事实上,它只是一个普通的(非嵌套、非内部、非匿名)Java 类。
I saw the term anonymous inner class before, but at that time, I didn't know what a regular anonymous class was.
不存在“常规匿名类”这样的东西。所有 Java 匿名类都是“内部”的。
正如 JLS 所说:
<小时/>"An inner class is a nested class that is not explicitly or implicitly declared static.
Inner classes include local (§14.3), anonymous (§15.9.5) and non-static member classes (§8.5)."
So, anonymous inner classes have to do with inheritance.
匿名内部类确实涉及继承,但这并不是它们成为“内部”的原因。见上文。
<小时/>I meant the "list.add(I meant the "list.add(new SomeObject());". All this time, I thought the object you added to the ArrayList, was called an anonymous class since we didn't name it.);". All this time, I thought the object you added to the ArrayList, was called an anonymous class since we didn't name it.
你错了。对象不是类1。
new SomeObject()
正在创建一个对象,而不是一个类。但这只是正常现象。就 JLS 而言,对象/实例没有名称。
现在变量和字段都有名称......但变量不是对象/实例或类。它们是名称和槽之间的绑定(bind),可以保存对对象的引用(如果类型声明允许的话)。
1 - 除了 java.lang.Class
实例的情况...即使这样,该对象也不是实际上来自的类/类型理论立场。
Or is it called simply an anonymous object and I had two mixed up?
不。对象没有名称。所有 Java 对象都是“匿名的”。这并不是一个有用的区分。 (请参阅上面我谈论变量的地方......)
<小时/>至于您的矩形
/正方形
示例,它们与匿名类、内部类、嵌套类或类似的东西无关。它们只是顶级类,使用普通的 Java 继承。 (并不是说我建议存在另一种“非普通”继承......)
关于java - 对匿名类与匿名内部类感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22725893/