Java 为什么我可以实例化抽象类和接口的对象?什么是超级构造函数?
这里我从两个抽象类和一个接口实例化对象。我想知道为什么我能在三种情况下做到这一点,特别是在没有抽象方法的NotShape类的情况下。第二个问题是,当我实例化NotShape类的对象时,“super”是什么?它属于对象类还是非形状类本身?我非常感谢你Java 为什么我可以实例化抽象类和接口的对象?什么是超级构造函数?,java,Java,这里我从两个抽象类和一个接口实例化对象。我想知道为什么我能在三种情况下做到这一点,特别是在没有抽象方法的NotShape类的情况下。第二个问题是,当我实例化NotShape类的对象时,“super”是什么?它属于对象类还是非形状类本身?我非常感谢你 abstract class Shape{ String descrOfShape = "This is a shape"; abstract void draw(); } abstract class 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);
}
}
您不是在实例化抽象类或接口,而是在实例化抽象类/接口的私有匿名扩展/实现
更多阅读:在这里,您将在主方法上实现接口或抽象类。您永远不能实例化抽象类或接口。但您可以从另一个类或接口继承(取决于继承规则)。在这里,您将实例化一个匿名类,这意味着您正在实现接口或扩展abstruct类。还有你的
@Override
void draw() {
}
及
它们显然是过度定义的超类(接口和abstruct类)方法。你可以试试这个,然后你可以看到它覆盖了你的printinfo方法
NotShape ns = new NotShape() {
@Override
void printInfo() {
super.printInfo(); /*What is the super? Is it belong to Object
class or NotShape class?*/
}
};
ns.printInfo();
这意味着您正在调用您的匿名类方法。然后调用你的super类,因为你调用的是super.printInfo()强>
NB:进一步研究突出显示的术语。谢谢
NotShape ns = new NotShape() {
@Override
void printInfo() {
super.printInfo(); /*What is the super? Is it belong to Object
class or NotShape class?*/
}
};
ns.printInfo();