java - 为什么我可以实例化抽象类和接口的对象?构造函数中的 super 是什么?
问题描述
在这里,我从两个抽象类和一个接口实例化对象。我想知道为什么我可以在三种情况下做到这一点,尤其是 NotShape 类没有抽象方法的情况。第二个问题是,当我实例化 NotShape 类的对象时,什么是“超级”?它属于 Object 类还是 NotShape 类本身?我非常感谢你。
abstract class Shape{
String descrOfShape = "This is a shape";
abstract void draw();
}
abstract class NotShape {
String descrOfNotShape = "This is not a shape";
void printInfo() {
System.out.println("Can't be measured");
}
}
interface Test{
int ID = 10;
void showResult();
}
public class InstantiateObjects {
public static void main(String[] args) {
Shape s = new Shape() {
@Override
void draw() {
}
};
NotShape ns = new NotShape() {
@Override
void printInfo() {
super.printInfo(); /*What is the super? Is it belong to Object
class or NotShape class?*/
}
};
Test t = new Test() {
@Override
public void showResult() {
}
};
System.out.println(s.descrOfShape);
System.out.println(ns.descrOfNotShape);
System.out.println(t.ID);
}
}
解决方案
您不是在实例化抽象类或接口,而是在实例化抽象类/接口的私有匿名扩展/实现。
更多阅读:https ://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
推荐阅读
- maven - 找不到 org.springframework.security:spring-security-b om:jar:5.0.6.RELEASE
- c++ - 将信号连接到基类的构造函数中的纯虚拟槽是否安全?
- sql - 根据另一列的日期范围更新列的最佳 SQL 方法。
- python - 在 django 中过滤外键
- javascript - 我更改网站语言的代码不起作用
- android - 在使用 Retrofit 和 GSON 进行解析时得到“预期 BEGIN_ARRAY 但在第 1 行第 1 列路径 $ 为字符串”
- javascript - package.json 的构建脚本
- angular - Mat-datepicker-toggle 显示在模态后面
- javafx - JavaFX ImageView 不刷新
- arrays - 使用 Powershell 对数组值进行排序