我们可以实例化一个抽象类? [英] Can we instantiate an abstract class?

查看:153
本文介绍了我们可以实例化一个抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了,我们只能通过继承它实例化一个抽象类,但我们不能直接实例化。
但是,我看到了我们可以通过调用另一个类的方法创建一个对象与抽象类的类型。
例如 - LocationProvider 是一个抽象类,我们可以通过调用 getProvider()在<$函数初始化它C $ C> 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");
    }
}

这可与接口了。

这篇关于我们可以实例化一个抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆