Friday, 25 November 2016

why java doesn't allow to create object for abstract class and interface ?

In interview, most of the people will explain about abstraction and interface, when interviewer ask why java doesn't allow to create object for abstract class and interface, all got struck. Here i  am gonna explain the reason with real time example.

The abstract class and interface represents the  more generic form or abstract entity, for example animal,vehicle and shape(It doesn't represent real entity). These abstract entity doesn't stand on its own. Because each animal (cat, lion,tiger, elephant, etc) ,vehicle(car, bus, aeroplane, train, etc) , Shape (circle, square, rectangle) which define its own property and behavior.  There's no such thing as a "pure" animal - there are specific types of animals . And you cannot call car as vehicle, does it make any sense in real time.

And also technically in java, abstract method may contain abstract method and implementation method. Just think, if java allowed you to create object, when you are calling the abstract method ,  what result it will deliver ? The same concept applicable for interface also.

Both the concept will be used to make proper design in the application in order to achieve more flexible and expandable.

Also you can use abstract and interface as template, sub class or real time entity can extend and built on it before you can use it.

Also some people say, abstract class and interface are incomplete class, so JVM doesn't know how much memory is required to create object. So it doesn't allow to create objects. This answer also acceptable.  But definitely, this is not a exact answer interviewer will look. So please give some real time example and explain in detail.








If you like the above solution . Please share this blog




No comments:

Post a Comment

s