Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the Java compiler not support inheritance of imports?

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).
like image 313
einpoklum Avatar asked Dec 28 '12 19:12

einpoklum


1 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.

like image 178
arshajii Avatar answered Oct 30 '22 12:10

arshajii