我们可以实例化一个抽象类?我们可以、实例、抽象类

2023-09-12 22:38:21 作者:只等待丶非懂爱

我看了,我们只能通过继承它实例化一个抽象类,但我们不能直接实例化。 但是,我看到了我们可以通过调用另一个类的方法创建一个对象与抽象类的类型。 例如 - LocationProvider 是一个抽象类,我们可以通过调用 getProvider()在 LocationManager 类:

I have read we can only instantiate an abstract class by inheriting it, but we cannot instantiate it directly. However, I saw we can create an object with the type of an abstract class by calling a method of another class. For example - LocationProvider is an abstract class, and we can instantiate it by calling getProvider() function in the LocationManager class:

LocationManager lm = getSystemService(Context.LOCATION_PROVIDER);
LocationProvider lp = lm.getProvider("gps");

是怎样的抽象类实例化吗?

How is the abstract class instantiate here?

推荐答案

您不能直接实例化一个抽象类,但你可以创建一个匿名类时,有没有具体的类:

You can't directly instantiate an abstract class, but you can create an anonymous class when there is no concrete class:

public class AbstractTest {
    public static void main(final String... args) {
        final Printer p = new Printer() {
            void printSomethingOther() {
                System.out.println("other");
            }
            @Override
            public void print() {
                super.print();
                System.out.println("world");
                printSomethingOther(); // works fine
            }
        };
        p.print();
        //p.printSomethingOther(); // does not work
    }
}

abstract class Printer {
    public void print() {
        System.out.println("hello");
    }
}

这可与接口了。

 
精彩推荐
图片推荐