本问题已经有最佳答案,请猛点这里访问。
当我创建抽象类的对象时,我必须这样做,就像一个接口一样。
AbstractClass abstractClass = new AbstractClass() {
@Override
public void abstractMethod() {
}
};
这是否意味着AbstractClass的对象是一个匿名的内部类对象?
这不公平的家伙,为什么?不管怎样,我得到了答案。我很快就会删除这个。
AbstractClass abstractClass = new AbstractClass() {
@Override
public void abstractMethod() {
}
};
这段代码意味着您正在创建一个扩展AbstractClass的匿名类。也可以对接口使用相同的表示法。
SomeInterface someImplementingClass = new SomeInterface(){/*some code here*/};
这意味着您正在创建一个实现SomeInterface的类。
注意,在创建匿名类时有一定的限制。由于匿名类已经扩展了父类型,所以不能像Java那样扩展另一个类,只能在类上扩展。
这段代码将有助于理解匿名类中重写方法的概念。
class Anonymous {
public void someMethod(){
System.out.println("This is from Anonymous");
}
}
class TestAnonymous{
// this is the reference of superclass
Anonymous a = new Anonymous(){ // anonymous class definition starts here
public void someMethod(){
System.out.println("This is in the subclass of Anonymous");
}
public void anotherMethod(){
System.out.println("This is in the another method from subclass that is not in suprerclass");
}
}; // and class ends here
public static void main(String [] args){
TestAnonymous ta = new TestAnonymous();
ta.a.someMethod();
// ta.a.anotherMethod(); commented because this does not compile
// for the obvious reason that we are using the superclass reference and it
// cannot access the method in the subclass that is not in superclass
}
}
这个输出
This is in the subclass of Anonymous
记住,anotherMethod是在创建为匿名类的子类中实现的。a是Anonymous型的引用变量,即匿名类的超类。因此,由于anotherMethod()在Anonymous中不可用,所以语句ta.a.anotherMethod();给出编译器错误。
对象不是类对象(在此上下文中)。它是从类派生的。在Java中,类和对象之间有区别,例如,基于原型的语言(例如JavaScript)不存在这种差异。
在您的示例中,您创建一个匿名类,创建该匿名类的一个对象,并将其赋给一个变量;全部都在一个步骤中完成。
匿名类总是内部类:http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html jls-15.9.5http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html jls-8.1.3
不能创建抽象类的对象。它们是不可实例化的。当您这样做时,您要做的是创建一种动态子类对象,并(同时)实例化它。或多或少,是的,您可以用与接口相同的方式创建它。有关详细信息,请参阅此答案。
实际上,您在这里创建了两个类:一个匿名的内部类,它扩展了AbstractClass,以及这个anonyomous类的一个实例,即对象。您不能也不能创建AbstractClass的实例。
还可以声明一个名为AbstractClass的变量,该变量具有AbstractClass类型。在这个变量中,您存储了新定义的AbstractClass子类的一个新创建的实例。
编辑:当然,您不能重用匿名内部类,因为它是匿名的,唯一可以创建或更确切地说创建它的实例的地方就在这里。
这里可能有一个循环或函数,在这种情况下,您可以创建这个匿名内部类的许多实例。但它仍然只是创建实例的这段代码。
抽象类没有任何实例(其类型的对象)。我建议Mavia查看以下链接以了解清楚性:http://docs.oracle.com/javase/tutorial/java/iandi/abstract.html
吸引类的一个基本特性是没有这种类型的直接实例。只能实例化实现类的完整接口的类。为了创建一个对象,首先需要一个非抽象类,方法是扩展抽象类。