When do we actually use the package keyword? What does it mean?
Suppose I write the following code:
package masnun;
public class masnun{
public static void main(String args[]) {
System.out.println("Hello maSnun!");
}
}
What does this package thing do? I get a masnun.class file that doesn’t run. I am new to Java. Can somebody please explain?
Thanks
As I’m not a fan of these other answers, I’ll write my own.
Real World Examples:
Think of a "package" as an easy way for a java class to reference another.
Let’s say I have this big box in my attic. I have a calculator, compass, protractor, etc. I can label this box
MathTools.Another example would be taking all your pictures and putting them in the
Picturesfolder in your documents. From there, you could split them intoSpring Break 2009or[Insert Name Here]'s Party.How does this relate to Java? Well, let’s look at the
java.utilpackage (you can reference this withimport java.util.*;. You have ArrayLists, Strings, Random, etc. which are used in most Java programs (common "utilities", if you prefer). There are all neatly organized into the same package, so that programmers can easily reference them (import java.util.*;).Easy Application:
Let’s assume that we can find all the files to a small dice simulator in
C:/Program Files/Java Project/my/proj/(it’s likely that this file doesn’t exist on your computer, but just pretend for a moment).You have 3 files:
Main.java,Dice.java, andDiceRoller.java. All of which are shown below:"C:/ProgramFiles/Java Project/my/proj/main/
Main.java":"C:/ProgramFiles/Java Project/my/proj/sims/
Dice.java":"C:/ProgramFiles/Java Project/my/proj/sims/
DiceRoller.java":Things to notice:
Main.javais packaged intomy.proj.mainDice.javais packaged intomy.proj.simsMain.javaneeds to importmy.proj.sims.Dicein order to create aDiceobject and use its methods because it’s in a different package fromDice.java.DiceRoller.javadoes not need to importmy.proj.sims.Dicebecause it is in the same package asDice.javaand the compiler will automatically associate the two.Importis a command to load the functionality of a class into the current file. Look atDice.java, for example. In order for it to create aRandomobject, which has the methodnextInt(), it needs to import the Random class from thejava.util.*package.You might notice that some people would prefer to use
java.util.*instead ofjava.util.Random,java.util.ArrayList, etc. What the*essentially means is any class withinjava.util. Runningimport java.util.*will import the Random, String, ArrayList, etc. classes.