Home » Java » Why should the Java compiler not support inheritance of imports?

Why should the Java compiler not support inheritance of imports?

Posted by: admin December 28, 2021 Leave a comment

Questions:

In Java, imports are related to an (outer) class, as every (outer) class is supposed to be coded in a separate file. Thus, one could claim that the import ...; directives before a class definition are associated with the class (somewhat like annotations are).

Now, if one could inherit a parent class’ imports, that would greatly reduce the clutter of source files. Why should this not be possible? i.e. why should the Java compiler not consider also the imports of base classes?

Notes:

  • There’s probably more than one answer.
  • I know this is not much of an issue if you let eclipse organize your imports, no need to mention that. This is about the ‘why’, not the ‘how’ (a-la-this).
Answers:

Firstly, it is important to note that not every class must be coded in a separate file – but rather that every public, top level class must be. And no, imports are not really associated with any class – they are just statements used to include certain external classes / packages within a file so that they can be used. In fact, you never need to actually import anything, you can always use the full name, i.e.:

java.util.List<String> list = new java.util.ArrayList<String>();

Imports are there for convenience (and only for the compiler – they are lost after the class is compiled), to save you from having to write all that out and instead only make you write List<String> list = new ArrayList<String> (after you make the relevant imports from java.util). Consequently, there is no reason why subclasses should ‘inherit’ imports.

###

Imports are syntactic sugar, nothing more. You could write any Java program without ever using an import statement if you really wanted to. For example, the following class compiles all by itself:

class Foo {
  java.util.List<String> list = new java.util.ArrayList<String>();
}

Additionally, inheriting imports makes it much, much harder to remove an import from a class. For example, if Bar.java inherits from Foo.java, you might not be able to remove an import from Foo without adding it to Bar. Forcing imports to be explicit makes it significantly easier to change a single file without worrying about the effects on other files, which is pretty much a fundamental principle of Java and object-oriented programming generally.

(This last point is related to issues that were a significant factor in the design of Go, which was specifically attempting to avoid the problems with C and C++ in this area.)

###

Having each file explicitly specify its imports improves readability. Imagine opening a file and not being able to see the dependencies at a glance, because the imports are inherited from another file.