this is the difference between static and non-static

Tuesday, September 2, 2008

Object class in Java should have been abstract

The Object class which is the super class for all the classes in Java should have been abstract. Going by principles of inheritance, a sub class has more functionality as compared to the super class. This is not true in Java. since it allows any one to create an abstract sub class of a concrete class. Which implies that one cannot create instances of a sub-class whereas the super-class allows instantiation.

So three changes would be required:
  1. abstract class should not be allowed to sub class from a concrete class
  2. non-abstract methods should not be allowed to be overridden to be abstract.
  3. Object class should be abstract
This is not a problem with Java alone, even other OOP languages also suffer from this drawback.

Whenever I talked about this to some of the Java developers their initial reaction was "how can Object be abstract, since it does not have abstract methods?". Well an abstract class need not have any abstract methods, only differences between the abstract and non-abstract classes are that an abstract can have all kinds of members which can be there in a non-abstract class, and it can additionally also have abstract methods. An abstract class can have constructors also, it may not be directly be used to create instances of the abstract class, but will still be used by the constructors of its sub class.

The change can easily be done in Java by imposing the restrictions in the compiler and as far as the existing code which uses instances of Object class directly is concerned, it could be updated to "new Object(){}" instead of "new Object()", wherever it appears.

No comments: