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.
Say you have two methods, one returning
foo.Locationand the other returningbar.Location(two completely different classes happening to have the same name, but in different packages – completely valid):When you can both of these methods in the same class and chain some methods, you don’t need an import:
It works because the compiler is completely sure which version (from which package) of
Locationare you using and it knows whereonlyInFoo()andonlyInBarare available.But suppose you need a local variable:
Now the compiler doesn’t really know
Locationdo you mean, so you must help him either by proceeding class name with package:or by importing that class:
You should now ask: what if I want to have local variable of both
foo.Locationandbar.Location? Well, you can’t import them both, obviously:What you can do is again: either don’t import at all and use fully qualified names:
…or import just one location: