首页 > 解决方案 > 为什么我可以实例化抽象类和接口的对象?构造函数中的 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);
    }
}

标签: java

解决方案


您不是在实例化抽象类或接口,而是在实例化抽象类/接口的私有匿名扩展/实现。

更多阅读:https ://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html


推荐阅读