When exactly do you need to import in java?

class, import, java-7, methods

Solution

Say you have two methods, one returning `foo.Location` and the other returning `bar.Location` (two completely different classes happening to have the same name, but in different packages - completely valid):

foo.Location getFooLocation();
bar.Location getBarLocation();

When you can both of these methods in the same class and chain some methods, you don't need an import:

if(getFooLocation().onlyInFoo()) {
  //...
}
if(getBarLocation().onlyInBar()) {
  //...
}

It works because the compiler is completely sure which version (from which package) of `Location` are you using and it knows where `onlyInFoo()` and `onlyInBar` are available.

But suppose you need a local variable:

Location location;
// much later
location = getFooLocation();

Now the compiler doesn't really know `Location` do you mean, so you must help him either by proceeding class name with package:

foo.Location location;

or by importing that class:

import foo.Location;

You should now ask: what if I want to have local variable of both `foo.Location` and `bar.Location`? Well, you can't import them both, obviously:

//WRONG
import foo.Location;
import bar.Location;

What you can do is again: either don't import at all and use fully qualified names:

foo.Location location1;
bar.Location location;

...or import just one location:

import foo.Location;

//...
Location location1;     //foo.Location
bar.Location location2;

Problem

The following unexpectedly compiled and ran without a problem: ``` import info.gridworld.actor.Actor; import java.util.ArrayList; public class ChameleonKid extends ChameleonCritter { public ArrayList<Actor> getActors() { ArrayList<Actor> actors = getGrid().getNeighbors(getLocation()); ArrayList<Actor> frontBack = new ArrayList<Actor>(); for(Actor i : actors) if(getLocation().getDirectionToward(i.getLocation())==getDirection()) frontBack.add(i); return frontBack; } } ``` The method getLocation() in the Actor class returns an instance of Location. And then I call the getDirectionToward() method of the Location class. `getLocation().getDirectionToward(i.getLocation())`. How does this work? I never imported the Location class. How am I able to work with it and call its methods? If that is how it works, when would I need to import a class? Only if I am instantiating it? I am using Java 7.

Original source