Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot use new keyword to initialize abstract class in Java?

I have read somewhere that we cannot initialize an interface, for example:

interface MyInterface{};

And the following code is definitely illegal:

MyInterface m = new MyInterface();

And as I remember the text I have read said: that because the new keyword is used to allocate memory for class members; so in case of interface, we only have abstract functions, so there is nothing to be allocated in an interface; therefore, initializing an interface is prohibited.

OK, that makes sense to me.

But in case of abstract class, we are allowed to declare and define abstract functions, non-abstract function, as well as normal variables;so why we also are not allowed to initialize an abstract class? And because of that, I was wondering when and how variables in an abstract class, if any, are allocated memory?

like image 211
ipkiss Avatar asked Sep 07 '11 14:09

ipkiss


1 Answers

No object is ever an instance of "just" an abstract class - it's always an instance of a concrete class. Otherwise you could call the abstract methods... and there'd be no implementation to be called.

The variables in an abstract class are allocated the same way as the variables of any other class which happens to be a superclass of the actual class being initialized - they live "with" the variables from the other classes in the hierarchy, basically.

EDIT: To clarify, this is a conceptual limitation as much as an implementation one. An abstract class usually contains abstract methods, which is the reason for making it abstract. The point of abstract methods is to allow the caller to have compile-time checking that the method will be there, even though the abstract class doesn't provide the implementation. The VM ensures that there is an implementation by preventing instantiation of "just" abstract classes.

Now abstract classes can also be used to prevent instantiation even if there aren't any abstract methods - basically the fundamental point of an abstract class is that it's one which can't be directly instantiated; only concrete subclasses can be instantiated.

like image 77
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet