The usage of the import statement is pretty trivial. It essentially allows us to "bring in" the functionality of classes not in our package.
For example, consider the classes below:
package wolfPack;
public class Wolf {
//Scary Code Here
}
package sheepHerd;
public class Sheep {
//Fluffy Code Here
}
We can import these classes into another package pretty easily.
import wolfPack.Wolf;
import SheepHerd.Sheep;
package jungle;
public class Jungle {
public static void main(String[] args) {
Sheep sheep1 = new Sheep();
Wolf wolf = new Wolf();
//TODO: fight code
}
}
Now, imagine that we had some non-public classes in the public class files above. Say, we wanted to create some smart Sheep that could tell when wolves were nearby. In other words, we add a SmartSheep
class in our Sheep.java
file.
package sheepHerd;
public class Sheep {
//Fluffy Code Here
}
class SmartSheep extends Sheep {
//Smart Code here
}
Now, how exactly would we go about importing the SmartSheep
into our Jungle
class? Will it be imported by simply typing import sheepHeard.Sheep
?