我们可以直接实例化一个抽象类吗? [英] Can we instantiate an abstract class directly?
问题描述
我读过我们只能通过继承来实例化一个抽象类,但我们不能直接实例化它.
但是,我看到我们可以通过调用另一个类的方法来创建一个具有抽象类类型的对象.
例如 - LocationProvider
是一个抽象类,我们可以通过调用 LocationManager
类中的 getProvider()
函数来实例化它:
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屋!