Can we instantiate an abstract class?

后端 未结 16 1166
长情又很酷
长情又很酷 2020-11-22 07:43

During one of my interview, I was asked \"If we can instantiate an abstract class?\"

My reply was \"No. we can\'t\". But, interviewer told me \"Wrong, we can.\"

16条回答
  •  渐次进展
    2020-11-22 08:22

    Extending a class doesn't mean that you are instantiating the class. Actually, in your case you are creating an instance of the subclass.

    I am pretty sure that abstract classes do not allow initiating. So, I'd say no: you can't instantiate an abstract class. But, you can extend it / inherit it.

    You can't directly instantiate an abstract class. But it doesn't mean that you can't get an instance of class (not actully an instance of original abstract class) indirectly. I mean you can not instantiate the orginial abstract class, but you can:

    1. Create an empty class
    2. Inherit it from abstract class
    3. Instantiate the dervied class

    So you get access to all the methods and properties in an abstract class via the derived class instance.

提交回复
热议问题