Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we instantiate an abstract class in Java?

I understand:

  1. Since an abstract class is nothing on its own, e.g. vehicle, we want to create an object of an concrete implementation, like Car, Bike, etc.
  2. The constructor of an abstract class gets called during object chaining.
  3. We can never directly create an object of an abstract class, even if it contains a constructor and all methods are implemented.

But from the compiler's perspective, why does Java enforce these rules?

like image 816
sandejai Avatar asked Feb 10 '14 15:02

sandejai


People also ask

Can we instantiate abstract class in Java?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .

What does it mean abstract class Cannot be instantiated?

An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along with the new statement. It may or may not contain an abstract method.

Why can't we instantiate an interface in Java?

You can't instantiate an interface or an abstract class because it would defy the object oriented model. Interfaces represent contracts - the promise that the implementer of an interface will be able to do all these things, fulfill the contract.


2 Answers

An abstract class is not complete! The author marked it abstract to tell you that some implementation is missing in the code. The author has done some of the work, but you must fill in some bits yourself to get it working. The abstract keyword ensures that no one would accidentally initiate this incomplete class.

Think of repairing a car. Someone has removed the brake pads and is going to replace them in the next day. Now, to prevent someone accidentally driving this car(which has no brakes installed), the mechanic installs a lock on the steering wheel. It's a fail-safe measure.

like image 142
kevin Avatar answered Sep 17 '22 20:09

kevin


This is not a technical limitation, rather (as you have pointed out) a logical one. Java (and many other languages) enforce various rules not because they are impossible to break, but because this is an intentional part of the language.

like image 25
Eli Iser Avatar answered Sep 18 '22 20:09

Eli Iser