If abstract classes can not be instantiated, exactly, what is this code: ABS clsAbs = new ABS () { [duplicate]

吃可爱长大的小学妹 提交于 2019-12-11 11:37:37

问题


I have a question about abstract classes.

First of all ... I'm using the google translator, sorry :( I hope you understand.

If abstract classes can not be instantiated, exactly, what is this code:

public class Ppal {

public void start(){

    ABS clsAbs = new ABS() {

        @Override
        public void absMetod() {
        }
    };

    clsAbs.metod();
}
}

ABS:

public abstract class ABS{

public void metod(){}
public abstract void absMetod();

}

ABS clsAbs = new ABS () {... Is not this an instance? clsAbs can be used and Abstract classes can not be used, only to create a model of abstraction ...

It could be used as anonymous class but this (ABS clsAbs = new ABS () {...) not anonymous.

Thank you very much in advance!


回答1:


You are instantiating an anonymous class that is extending the class ABS. And you can instantiate this anonymous class because it defines all the abstract methods in ABS(Thanks Nebelmann)

It is the same if you create a class like public class Foo extends ABS that implements the absMetod()

and you can do: ABS bar = new Foo()




回答2:


All you need to understand is this

ABS clsAbs = new ABS() {

        @Override
        public void absMetod() {
        }
    };

you are implementing the abstract method absMetod() while creating anonymous class that extends ABS class



来源:https://stackoverflow.com/questions/14457076/if-abstract-classes-can-not-be-instantiated-exactly-what-is-this-code-abs-cls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!