Creating and Using Packages

To organise a class into a package we use the package keyword. The package corresponds with the directory name relative to the parent folder.

Example

Here is an example of the Main class defined in the package edu.self package :

package edu.self;

public class Main {

    public static void main(String[] args) {
    }
}

and here is the folder structure on the operating system :

Directory Structure

  1. src is the parent directory
  2. edu is the parent package
  3. self is the sub package defined in the edu package.

Packages can be nested as in the above case by using a dot, (.). The directory structure will have to correspond.

Using Packages Members

To use a class or interface defined in the package they will need to be imported. The members are imported using the import keyword. Members in the java.lang package do not need to be imported, they are available automatically.

The import statement should come after the package statement and before any class definitions.

Importing a Class

After adding the Socket.IO library to our project we will have access to the classes and interfaces of the library.

To use the Socket class, defined in the package, package io.socket.client, we can import it as follows :

import io.socket.client.Socket;

Now we have access to the Socket class in our code.

Instead of imported we can also refer to the member by its fully qualified name as follows :

io.socket.client.Socket socket;

Importing Entire Package

Or we can import the whole package by using the asterisk, *.

import io.socket.client.*;

Apparent Hierarchies of Packages

Packages appear to be hierarchical but they are not. Package naming is used to show relationships but not show inclusion.

Importing io.socket.* imports all the types in the io.socket package, but does not import io.socket.emmiter or io.socket.client packages.

Name Ambiguities

If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name.

In our chat application, they are two Socket classes, one is defined in the io.socket.engineio.client and another in the io.socket.client. To use both in our class, the Socket class will need to be fully qualified as follows :

io.socket.client.Socket clientSocket;
io.socket.engineio.client.Socket engineSocket;

Static Import

Static methods and fields can be imported so that they can be used without their class or interface prefix by using the import static keyword.

We can import the static abs method in the java.lang.Math class as follows :

import static java.lang.Math.abs;

Now we can use the abs method anywhere without prefixing it with the Math class as follows :

import static java.lang.Math.abs;

public class Main {
    public static void main(String[] args) {
       int a = abs(-10); //now we can use without typing Math.abs()
    }
}

results matching ""

    No results matching ""