Using java api packages

Java Packages Tutorial

In this Java tutorial we learn how to group related classes into packages to help control access and avoid naming conflicts.

We discuss how to manually create a package in Java or how to do it in an IDE like Eclipse. Then we look at how we can use the packages and subpackages.

What are packages

A package in Java is used to group related classes together. Packages help avoid naming conflicts, control access, makes searching program elements (classes, interfaces, enums and annotations) easier and helps us maintain our code.

We can think of packages as a folder in a directory where we store related class files. The folder then becomes a package that contains the class files inside, grouped together.

A package also creates a namespace automatically, which means if two classes have the same name, but are located in different packages, the names won’t conflict with each other.

There are two types of packages in Java:

How to manually create a package in Java

There are several options to create a new package in Java.

If you’re not using an IDE, you will need to execute the following command in the terminal.

 javac -d package_folder file_name.java

The package_folder is the folder that all the related classes, interfaces, enums and annotations will be stored.

Inside the file_name.java file, we need to mark the package in the source code with the same name as the package_folder.

To mark a package, we use the package keyword, followed by the name, at the very top of a java document.

There can only be one package definition in each source file and it applies to all types in the file.

If we don’t define a package statement, all the types in the file will be placed in the ‘default’ package.

 A popular naming convention, and considered good practice, is to name our packages in all lowercase, to avoid any conflicts.

In this tutorial course we’re using the Eclipse IDE, which makes it easy for us to create packages.

Читайте также:  Среда разработки приложений php

If you’re using a different IDE, like Netbeans or IntelliJ, please refer to their documentation for the steps to follow to create a new package.

How to create a package in Eclipse IDE

To create a new package in Eclipse, go to File > New > Package.

In the New Package window, it will ask us to specify the package location and name. The location should already be populated with the directory you’re currently working on.

For the name we’ll choose ‘demo’ and click on the Finish button to create the new package. Eclipse will automatically create the appropriate directory for us.

New Java Package window in Eclipse

If we expand our project in the Project Explorer, we should see the new empty package.

Empty package in Eclipse Project Explorer

The next step is to add classes to our package. Go to File > New > Class.

In the New Class window, select ‘demo’ as the Package, name the class ‘Logger’ and click on the Finish button to create the new class.

Link a package to a new Java class in Eclipse

The class should open in the Code Editor window. It will have the package defined as ‘demo’ and the class defined as ‘Logger’.

Any class that we associate with the ‘demo’ package, will be stored in its directory.

How to import a package in Java

Before we import our new package into the main program, lets add some code to the class first.

In the ‘demo’ package, in the ‘Logger’ class, add the simple method below.

To import the package into our main program, we use the import keyword, followed by the package name. Then, with dot notation, we access the specific class we want to import.
 If we need to, we can import all the classes in a package with the asterisk * wildcard operator.
 The asterisk after the dot operator simply means: import all from package_name.
     The whole ‘Logger’ class is now available to us to use as we normally would.

It’s good practice to separate each class in your program into a separate class file, and group related classes into packages. It keeps your code organized and easy to find.

Subpackages in Java

We can create packages within packages to separate and organize our classes even more.

For example, we could create a package called ‘vehicles’, with subpackages for cars, trucks and motorcycles.

Typically, a company uses its domain name in reverse for packages. For example, if the company domain name is ford.com , the packages would be: com\ford

So we would end up with a directory structure like:

com\ford\vehicle\car\mustang com\ford\vehicle\suv\everest com\ford\vehicle\commercial\ranger

which we would reference in our IDE as packages and import them with multiple levels of dot notation.

Java provides us with many useful packages to help create our applications. We import and use them in the same way as custom packages.

We will go through several packages throughout the rest of the tutorial course, when and where they’re needed.

You can also see a list of all the available packages for Java 13 or the Java 13 foundation packages from the official Java documentation.

Summary: Points to remember

  • A package is similar to a folder in a directory, and groups related classes, interfaces, enums and annotations together.
  • To associate a class with a package, we mark the top of the document with the package keyword and its name.
  • To import a class from a package, we use the import keyword and the class name with dot notation, following the directory structure.
    • To import all classes from a package we can replace the class name with an asterisk wildcard.
    • Typically a reversed domain name is used as directory structure.

    Источник

    Java Packages

    A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

    • Built-in Packages (packages from the Java API)
    • User-defined Packages (create your own packages)

    Built-in Packages

    The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.

    The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.

    The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.

    To use a class or a package from the library, you need to use the import keyword:

    Syntax

    import package.name.Class; // Import a single class import package.name.*; // Import the whole package 

    Import a Class

    If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:

    Example

    In the example above, java.util is a package, while Scanner is a class of the java.util package.

    To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line:

    Example

    Using the Scanner class to get user input:

    import java.util.Scanner; class MyClass < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); System.out.println("Enter username"); String userName = myObj.nextLine(); System.out.println("Username is: " + userName); >> 

    Import a Package

    There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.

    To import a whole package, end the sentence with an asterisk sign ( * ). The following example will import ALL the classes in the java.util package:

    Example

    User-defined Packages

    To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:

    Example

    └── root └── mypack └── MyPackageClass.java

    To create a package, use the package keyword:

    MyPackageClass.java

    package mypack; class MyPackageClass < public static void main(String[] args) < System.out.println("This is my package!"); >> 

    Save the file as MyPackageClass.java, and compile it:

    This forces the compiler to create the «mypack» package.

    The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign » . «, like in the example above.

    Note: The package name should be written in lower case to avoid conflict with class names.

    When we compiled the package in the example above, a new folder was created, called «mypack».

    To run the MyPackageClass.java file, write the following:

    Источник

Оцените статью