Java Packages In Full Detail With Programming Examples

Java Packages:

Packages in java allow classes to the group. Do you want the class (es) of a Java file to be part of a Package assignment, you need to keep two things in mind: First, type as first (!) instruction in the Java file to which package it belongs. To do this, use the package keyword as follows:

package packagename;

On the other hand, the corresponding Java file must also be based on the Project path in a directory with the same name as the Package. Sounds like a hassle, but it’s not that difficult if you have one use a modern development environment such as Eclipse, which synchronizes the package structure and file system automatically ensures.

Do not specify a package in a Java file – as has been the case so far war – it is located in the so-called default package. Is in the file system this Java file usually directly in the project directory. For our previous mini-projects that is acceptable. It’s not worth it here To think about the classification of the classes in java Packages, especially then not if the project only consists of a single one anyway Class exists. But if you have a project with multiple classes, bid Java Packages the possibility of structuring them. The project remains clear and easier to maintain.

For large projects, a flat arrangement of java Packages is insufficient. In such cases, Java allows a package hierarchy. Java Packages can therefore have sub-java Packages, whereby the nesting depth almost can be of any size. Please overdo it with nesting but not. If you think you have more than five java Packages in Having to go deep, do something wrong, or your program is so gigantic that Microsoft has to tremble before you. To java Packages  nested in the program, you must single package hierarchies in the package statement with a Separate period as in the following example:

package upperpackage.interpackage.sub-package;

In addition to a better project structure, java Packages offer another one Advantage: You separate namespaces. So classes only have to be within of a package that have a unique name. Introduce yourself Project with 2000 classes ahead, then you will appreciate this advantage. However, this has consequences: Do you want a class from one If you are using another package, you must use the fully qualified class name specify to address them. The fully qualified class name consists of the package name, with the individual hierarchy levels are separated from each other by a point; it is followed by a period and finally the class name. An example:

The class Abc holds an attribute of the type Xyz. Are Abc and Xyz in different java Packages, the fully qualified name must be in Abc specified by Xyz. If Xyz is in the package op.zp.up, is the fully qualified name op.zp.up.Xyz. But there is one more Another, more common option to integrate Xyz: the import Instruction. import statements must be in Java files before the definition of the class (es). It looks like this:

If a class is referenced from another package, it is usually used several times within the referencing class. From this perspective, the use of the import Instruction more advantageous, since the fully qualified class name is not constantly must be specified, which makes the source code confusing would. But you cannot avoid using fully qualified class names to use when two classes with the same name come from different Java Packages should be referenced. Two import statements in one Class that refer to two identical class names are not allowed and also not useful.

There are restrictions when using classes from other java Packages. You can only use classes that are public. At all previous class definitions, we each have the keyword public. If we leave this out, the corresponding ones have used Classes no longer visible outside of their package. The visibility can not only be restricted by attributes and methods, but also with classes, but here in a less differentiated way and way. In the case of attributes and methods, a distinction is made between public, protected, private, and no indication. With classes, there is only public or no specification.

The Java class library has a special package whose Classes are imported by default. It is about that Package java.lang. This package includes a number of fundamental Classes for the Java programming language. Some of these classes have we have already used in one place or another (without us had to specify a corresponding import statement) or become still use them on the following pages. Important classes from this Package are for example System, Object, String, Math, and Exception.

That brings us to the last topic of the peach section. Let’s talk about cohesion and coupling. Cohesion means the Number of dependencies within a system while the coupling is determined by the number of dependencies between systems. In the context of Java programming, systems are concretely understood non-atomic program units, i.e. program units that can be dismantled and thus consist of additional program units: from Classes and Packages. Classes, in turn, consist of attributes and Methods and java Packages consist of classes or sub-packages. She can also include methods that are derived from local variables consist. Elementary variables/attributes (of type int, double, etc.). They are as the name suggests elementary or atomic.

It is said that a good design is characterized by high cohesion and low coupling; i.e. the components of a system should have many dependencies between the systems, however, it should only have few dependencies. Considering that the systems, that we think are hierarchically arranged, that it’s systems, this requirement is contradictory. On (abstract) For example:

java packages

This sample program is used to explain the terms cohesion and Coupling very well suited. First, consider Class A. It is the single class where the figure shows the components. For all In other classes, the internals is hidden for better clarity. As you can see, the components of Class A are strongly interwoven. The components (attributes, methods) have has many dependencies on the other components in the system. Cohesion is therefore high. That’s good. The component has only one relationship to class M. The coupling of Class A to other systems is therefore low and low coupling is also good. In the case of coupling, by the way, one speaks less of low and high, but instead rather of loose and narrow. In this respect, we should Better say: The loose coupling is also good.

Let’s look at package p1 next. Now the just mentioned Contradiction between high cohesion and loose or low coupling visible. From the point of view of class A, it was just as important to us. outwards, i.e. at the package level, as few dependencies as possible, and from the point of view of the package, we want their cohesion to maximize. We strive for as many relationships as possible between the classes within the package.

To understand what cohesion and coupling mean, you need to one is looking at the whole system from the inside out and the other understand the requirements as relative requirements. Try Let’s look at that. We start inside, which is the classroom. On Design in a class, it is important that the attributes and methods have many relationships, as otherwise, the question would arise, Why you should encapsulate them in a class, or not? But it would be better to divide them into different classes. The components a class must work together, otherwise, they will not a common class. We strive towards the outside as far as possible a few relationships. This reduces the complexity of the systems. Due to a few external relations, the entire system easier and more flexible when making changes. After the classes are designed and relations are defined to the outside, we want to place them in java Packages. We are now taking those classes, which are highly correlated – i.e. mutually are strongly related. In this way, we achieve a high Cohesion in the package and at the same time (!) a loose coupling to other Java Packages. Analogously, we proceed when we have several packages to one group.

What has been done so far with regard to the design of object-oriented software architectures? refers only to technical aspects. But unfortunately, it is only half the truth. We must ensure that our Classes also take content aspects into consideration. Consider the sample architecture again. The theories of cohesion alone and coupling, we could not justify why we need an additional Define package p2 instead of simply integrating its classes into p1.

Because: p2 has an internal relationship and an external relationship. It is not easy to infer that there are many internal relationships It has very few external relations. But let’s get away with it that p1 defines classes for graphical user interfaces (e.g. Button, Text Box, Listbox) and in p2 classes for file access, it is appropriate in any case to use such different codes – from Reasons – to distribute to different java Packages.

In practice, it is admittedly not easy to have a good class design to be found. Usually, you need a lot of experience. Want to If you want to design larger software architectures, you should to tackle theories such as cohesion and coupling, so you can get an idea of where your Architecture is supposed to go.

Creating java packages:

A package is a collection of classes. An example, the package java.lang, which supports certain standard classes (such as String) contains. It is the only package that the system does automatically is involved. Another package that we have been using for a long time is Prog1Tools. This class collection contains the IOTools that we use for the Use keyboard input. Because the package is not from Sun or Oracle comes from and was not included with the Java installation, we have it have to install afterward. If we want to define our own package – in the following, we call it simplicity half a mypackage the easiest way to proceed is as follows:

  • In our working directory, we create a subdirectory called mypackage. In this directory, we save all files with the extension java describing the classes of this package.
  • We want to create a new class myclass that is part of the package mypackage should belong, we create a file in the mypackage subdirectory called We write on the first line package mypackage;

and tell the compiler to which package our class belongs. All other Java Instructions (import statements, the class definition) must follow the package statement. Before the instruction is allowed at most Comments are located.

  • We translate our class from the working directory – not from the subdirectory! The call

javac -d . mypackage/

javac -d . mypackage\

under Windows creates a file myclass.class and saves it in Mypackage directory. When we go through the class in other programs the instruction

import mypackage.myclass;

want to include, thanks to the directory structure, the system knows where the class file. If (as in all our earlier programs) the package statement is omitted, so the class belongs to an unnamed package, the so-called Standard package. It was not, of course, for our little exercises it is necessary to define a special package. However, if we consider that Millions of people use Java, we can imagine that class names like a test, myprog, or foo can certainly be used more than once. Packets allow us to make a precise distinction. There are usually also certain conventions for naming Java Packages. With our package name Prog1Tools, for example, we have violated this, since the web address of the programmer from it does not apply is seen. However, these conventions are for the novice programmer with more effort than benefit and are therefore not discussed at this point implemented.

Standard library packages:

The standard library classes are in java Packages that start with java and javax start. Java.awt.Point is in a package of the Standard library, which can be recognized by the java part. If someone would put their own classes in java Packages with the prefix java, java.ui, for example, it would cause confusion, nothing more It is clear whether the package is part of every distribution. Classes that begin with javax do not necessarily have to be Java SE belong.

import java Packages declaration:

To use the Point class, which is in java.awt package, outside of the To use the java.awt package – and that is always the case for us users, it must be known to the compiler with the entire package specification be made. The class name alone is not sufficient for this, because it may be that the class name is ambiguous and one Class declaration exists in different java Packages. (In Java There are a few examples in the library, such as java.util.Date and java.sql.Date.) In order for the compiler to precisely assign a There are two ways to enable a class to a package: To one can fully qualify the types, as we have done so far to have. An alternative and more practical option is to use the Compiler with an import declaration on the types in the package to draw attention to:

Awt Without Import

Awt With Import

Access all types of a package with import p1.p2. *:

A Java class accesses several other types of the same package back, the number of import declarations can become large. In our example, we only use two classes with Point and Polygon from java.awt, but you can quickly imagine what happens when additional windows from the package for graphical interfaces, Labels, buttons, sliders, etc. can be integrated. The solution, in this case, is a *, which is the last link in an import Declaration can be: import java.awt. *;

import *; With this syntax, the compiler knows all types in Package java.awt and, so that a class Point and Polygon is well known, as is the File class.

The * shortens the number of individual import declarations, but it’s good to keep two things in mind:

  • If two different java Packages have the same type of host, such as Date in java.util and java.sql, so comes a translation error occurred when using the type. Here must be fully qualified.
  • The number of import declarations says something about the degree of complexity. The more import declarations there are, the more the dependencies on other classes become greater, which is what Is generally a warning sign. Graphic tools show the Dependencies exactly, but an import * can only hide once.

Hierarchical structures using java Packages :

A Java package is a logical grouping of classes. Leave packets are organized in hierarchies, so that in one package another package can be located; this is the same as for the directory structure of the file systems. In the standard library, the java package is a Main branch, but this also applies to javax. Below the java package then, for example, the java Packages awt and util, and are under javax then swing and other subpackages.

The classes that belong to a package are normally[ 113 ] in the same directory. The name of the package is then the name of the directory (and vice versa, of course). Instead of the directory separator (for example “/”or”\”), a dot appears. Let’s assume the following directory structure with a helper class: com/tutego/

com/tutego/DatePrinter.class Here is the package name com.tutego and is the directory name com/tutego/. Umlauts and special characters should be avoided, as they are kept on the file system for Trouble. But designers should always be in English anyway in the same way.

The structure of package names:

In principle, a package name can be anything, but there are hierarchies usually made up of upside-down domain names. From the domain to The website becomes com.programmingdigest. This Naming ensures that classes are also unique worldwide stay. A package name is usually completely lowercase.

The package declaration:

To put the DatePrinter class in a com.programmingdigest package, two things must apply:

  • It must be physically located in a directory, i.e. in com / programmingdigest /.
  • The source code contains a package declaration at the top.

The package declaration must be at the very beginning, otherwise, there is a translation error (of course comments in front of the package declaration).

Example: com/programmingdigest/

After the package declaration, as usual, import Statements and the type declarations. As is known, there are two options for using the class: once via the full qualification and once via the import Declaration.


And the variant with the import declaration:


Unnamed package (default package):

A class without a package specification is in the unnamed package (unnamed package) or default package. It is a good idea, always organize your own classes in java Packages. That also allows finer visibilities, and conflicts with other companies and Authors are avoided. It would be a big problem if a) each Company confusedly puts all classes in the unnamed package and then b) tried to swap the libraries: would be conflicts preprogrammed.

java packages


A class that is in the package can be any other visible class from other packages, but no classes from the unnamed package. Let’s take Sugar in the unnamed package and Chocolate in the

Package com.programmingdigest to: Sugar.class

com/programmingdigest/Chocolate.class The class Chocolate cannot be Sugar because classes from the unnamed package do not apply to subpackages are visible. Only other classes in the unnamed package can Use classes in the unnamed package. Now stand Sugar in a package – which can also be a top package!

so that would be possible again and Chocolate could Sugar import.



Classes with the same name in different java Packages  *:

There is a problem with several identically named classes in different java Packages. Full qualification is required here. So give in the java.awt and java.util packages. A simple import java.awt.* and java.util.* does not help because the Compiler does not know if the GUI component or data structure means. Also, an import does not say anything about whether the classes in of the importing file. The same applies to: the class Date, which appears once in java.util and once in java.sql can be found. Funny enough, java.sql.Date extends the class java.util.Date. That the compiler doesn’t get confused here, is easy to explain not only by name but also by of their java Packages. The compiler always considers a full Qualify.

Compilation Unit:

The package and import declarations don’t really belong to the Type declaration that is just a class C {} or related Includes type declarations. In fact, that’s all Components of a compilation unit. So there is a compilation unit from at most one package declaration, and many import declarations and any number of type declarations. A is ultimately a collection of compilation units.

Static import *:

The import informs the compiler about the java Packages so that a type no longer has to be fully qualified if it is explicitly specified in the import part or when the package is named. If a class prescribes static methods or constants, their properties are always addressed via the type name. It With the static import, there is now the option of importing the static Use methods or variables without type names immediately. This is practical, for example, for screen output when the static variable out from the system is integrated: import static java.lang.System.out; In the otherwise usual issue of System.out.printXXX (…) can after the static import of the Class names are omitted and the out.printXXX (…) remains:


Related Article:

Java Class And Object With Programming Examples

break and continue: java break label and continue label with examples

java while loop and java do while loop with programming examples

Java for Loop Statements with Programming Examples


Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button