What Is the Purpose of Defining a Package in a Java File

What is the purpose of defining a package in a Java file?

Let's start with the definition of a "Java package", as described in the Wikipedia article:

A Java package is a mechanism for
organizing Java classes into
namespaces similar to the modules of
Modula. Java packages can be stored in
compressed files called JAR files,
allowing classes to download faster as
a group rather than one at a time.
Programmers also typically use
packages to organize classes belonging
to the same category or providing
similar functionality.

So based on that, packages in Java are simply a mechanism used to organize classes and prevent class name collisions. You can name them anything you wish, but Sun has published some naming conventions that you should use when naming packages:

Packages

The prefix of a unique package name is
always written in all-lowercase ASCII
letters and should be one of the
top-level domain names, currently com,
edu, gov, mil, net, org, or one of the
English two-letter codes identifying
countries as specified in ISO Standard
3166, 1981.

Subsequent components of the package
name vary according to an
organization's own internal naming
conventions. Such conventions might
specify that certain directory name
components be division, department,
project, machine, or login names.

Examples:

  • com.sun.eng

  • com.apple.quicktime.v2

  • edu.cmu.cs.bovik.cheese

Why do java source files require package declarations?

As you (implicitly) acknowledged, you are not required to declare the name of a package in the case of the default package. Let us put that quibble aside ...

The reason for this seeming redundancy is that without a package declaration, the meaning of Java1 source code would be ambiguous. For example, a source file whose pathname was "/home/steve/project/src/com/example/Main.java" could have 7 different fully qualified names, depending on how you compiled the code. Most likely, only one of those will be the "correct" one. But you wouldn't be able to tell which FQN is correct by looking at (just) the one source file.


It should also be noted that the Java language specification does not require you to organize the source code tree according to the packages. That is a requirement of a (large) family of Java compilers, but a conformant compiler could be written that did not require this. For example:

  • The source code could be held in a database.
  • The source code could be held in a file tree with random file names2.

In such eventualities, the package declaration would not be duplicative of file pathnames, or (necessarily) of anything. However, unless there was some redundancy, finding the correct source "file" for a class would be expensive for the compiler ... and problematic for the programmer.

Considerations like the above are the practical reason that most Java tool chains rely on file tree structure to locate source and compiled classes.


1 - By this, I mean hypothetical dialect of Java which didn't require package declarations.

2 - The compiler would need to scan the file tree to find all Java files, and parse them to work out which file defined which class. Possible, but not very practical.

Why did we have to declare a package at the top of the code?

What exactly did we solve adding package bucky?

By adding package you specify in which folder your class is located.

I mean we are moving a class named apples.java, why are we especially
moving class for example?

The Eclipse IDE is telling you a way to solve your error by moving your class to a good package...

Take a look at this tutorial

What is the relationship between package and jar file in java?

Package consist of classes..

Jar : collection of packages and classes...

How do i create a package in java?

If you work with an IDE, it should help a lot.

In Java, a package is a declaration at the start of your class files. It also matches the folder hierarchy where this file is stored, from your project's root (source path).

e.g. to declare class MyClass in package foo.bar, you do it in file foo/bar/MyClass.java:

package foo.bar;

import whatever.other.classes.you.need;
...

class MyClass {
...
}

Package in Java

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 Pictures folder in your documents. From there, you could split them into Spring Break 2009 or [Insert Name Here]'s Party.

How does this relate to Java? Well, let's look at the java.util package (you can reference this with import 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, and DiceRoller.java. All of which are shown below:


"C:/ProgramFiles/Java Project/my/proj/main/Main.java":

package my.proj.main;

import my.proj.sims.Dice;

public class Main
{
public static void main(String[] args)
{
DiceRoller roller = new DiceRoller();
roller.rollAndShow(4);
}
}

"C:/ProgramFiles/Java Project/my/proj/sims/Dice.java":

package my.proj.sims;

import java.util.Random; // I used the Random class, but you can also use the Math class if you prefer (java.lang.Math)

public class Dice
{
public Dice()
{
}

public int roll()
{
Random rand = new Random();
return rand.nextInt(6) + 1; // Rolls a random number 1-6
}
}

"C:/ProgramFiles/Java Project/my/proj/sims/DiceRoller.java":

package my.proj.sims;

public class DiceRoller
{
public DiceRoller ()
{
}

// Rolls and prints the result of 'n' number of rolls
public void rollAndShow(int n)
{
Dice dice = new Dice();

for (int i = 0; i < n; i++)
{
System.out.println(dice.roll()); // You should never use S.o.p in a method - it's bad practice, but it's easier this way if you don't yet understand the concept of objects
}
}
}

Things to notice:

  • Main.java is packaged into my.proj.main
  • Dice.java is packaged into my.proj.sims
  • Main.java needs to import my.proj.sims.Dice in order to create a Dice object and use its methods because it's in a different package from Dice.java.
  • DiceRoller.java does not need to import my.proj.sims.Dice because it is in the same package as Dice.java and the compiler will automatically associate the two.

Import is a command to load the functionality of a class into the current file. Look at Dice.java, for example. In order for it to create a Random object, which has the method nextInt(), it needs to import the Random class from the java.util.* package.


You might notice that some people would prefer to use java.util.* instead of java.util.Random, java.util.ArrayList, etc. What the * essentially means is any class within java.util. Running import java.util.* will import the Random, String, ArrayList, etc. classes.

Java: What would be the consequence of leaving the package statement out?

Why can't Java figure out itself to which package a class belongs? Why is the additional package statement needed?

packages are required to resolve the class name conflicts and load the correct class by the class loaders (inside JVM) into the memory.

Assume that you have created two classes with same name as Utils class (one Utils class for Maths and one Utils for Physics), then JVM during class loading time must know & resolve which of this Utils class need to be loaded/required. That's where packages will come to the rescue and you can define com.maths.utils and com.physics.utils packages and add the Utils class into the right package so that we can use it later in any other class by using import keyword to specify which Utils we are referring to i.e., in short, packages provide the complete full name to the class file.

  • Multiple classes (related to same functionality) can be grouped as
    packages.
  • Multiple packages (related to same functionality) can be grouped as
    JAR file.

What happens if I have nested packages and I DO NOT write a package statement in one of the contained classes?

If you have nested packages and if you dont write the package name using the package keyword at the top of the class, then the code will not compile.

I suggest you read here more on this.

Do I have to use package term in every class?

You never need to put a class in a package. However, it is almost always a good idea. This is something that Netbeans aggressively tries to encourage you to do.

For small projects, using the default package (that is, a file without a package statement) is OK. However, once your project grows and starts adding external libraries, bad things can happen. What if someone else decided to use the default package and happened to have an identically-named class? Now, since you're both in the same package, collisions can occur!

Your file structure should also reflect your package. That is, a file in package com.myurl.helloworld should be located in a folder called com/myurl/helloworld. This is for the same reasons as above.

Also, and you probably haven't gotten here in your studies, you cannot import classes from the default package, or use the package-private visibility modifier in a default package class.



Related Topics



Leave a reply



Submit