Can I get a clear explanation why why can’t we instantiate an object of an abstract class. I know abstract is not real. But I want to know more why can’t we instantiate an object of an abstract class.
2
It’s because an abstract class isn’t complete. One or more parts of its public interface are not implemented. You’ve said what they’re going to be – what they’re called, what their name is, what they return – but no implementation has been provided, so nobody would be able to call them.
Compilers prevent you from instantiating such incomplete objects on the basis that if you do instantiate an object you’re going to want to use its entire public interface (this assumption is related to the idea that an object should do a minimal set of things, so that the public interface is not too large to manage). It’s also a useful safety net. The compiler says “hang on, this is just part of a class, you need to provide the rest of it”.
Say the C# compiler was modified to allow you to instantiate abstract classes. Presumably it would fill in the missing definitions with some stub code. This being C#, I suspect that code would just throw System.NotImplementedException
. This is not particularly useful, and also an error you wouldn’t be able to find until runtime. Finding it a compile time is far more likely to get you a program that works.
And that’s not even thinking about the possibility that one of the concrete methods provided by the abstract class happens to call one of the abstract ones that you decided you didn’t need to write.
2
Because an abstract class by design usually has a unimplemented method. What should the program do if someone tried to call it?
Having unimplemented methods on an object is usually a bug so the compiler helps you by not allowing them to exist.
If you want to throw an error when the method is called then just implement it with just throws new UnsupportedOperationException();
as the implementation.
If you don’t want to create a new class you can instead use an anonymous class:
AbstractFoo foo = new AbstractFoo(param, for, constructors){
@Override
public void foo(){
//override and implement methods
}
};
This will create a concrete class behind the scenes which will be used.
1
Let me answer your question with another question: What would happen when you call any of the abstract methods?
2