I came across some java code where the following statement was present.
com.myproject.bar.Foo foo = new com.myproject.bar.Foo();
The class com.myproject.bar.Foo
has not been imported into the class but an object of Foo
is created in the class where this statement is written.
Why has such an implementation been done? Are there any advantages of using such an implementation over doing an import of the class Foo
?
An import statement just makes the type available by its short name without specifying the package. That's all it does. It's not like the class can't be used without an import.
Usually it's clearer to use an import instead, but sometimes that's not possible - you may want to use two classes both called Foo
from different packages with the same class, for example. (This is most common when you've got two representations of the same entity - an API representation and a storage representation, for example.)
Without knowing what the real code looks like, we can't tell whether that was the case here, or whether an import would have been fine. If it can work, an import is usually more readable.
See more on this question at Stackoverflow