Skip to content

Is instantiating an instance of an abstract class a runtime or compilation error?

From my understanding, no objects are instantiated in compilation time. Hence, the error should be classified as a run time error when the instance of the abstract object is created in runtime. Am I correct or will such an error be picked up by the compiler before runtime?

Answer

The work of compiler basically boils down to accepting your java code as an input and producing a valid byte code that later can be loaded into/run by the JVM. When you create an instance of Abstract Class at the level of code the compiler can’t really produce a valid bytecode and hence it complains.

So bottom line, the compiler doesn’t really try to create your object. It only tries to translate what it sees into the valid bytecode and in this case it can’t…

Now if you use reflection, for example, where all the class names are strings or even calculated in runtime, then the compiler won’t be able to detect such a mistake and will compile your code successfully. But then, when you run a program the error will arise, this time it will be a runtime error – a result of an attempt to create an instance of an abstract class.