• No results found

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

N/A
N/A
Protected

Academic year: 2021

Share "WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods."

Copied!
8
0
0

Loading.... (view fulltext now)

Full text

(1)

Java Packages

KNOWLEDGE GOALS

Understand what a package does.

Organizes large collections of Java classes

Provides access control for variables and methods using the modifier 'protected' Helps manage large applications

Supports code reuse Know how packages are used.

The Java platform code libraries are packages Package java.lang is imported by default

Packaged classes maybe be used by fully qualified names Packages may be imported to access all classes

Know how to build a package.

A package statement at the start of Java source puts its classes in a package The package name must follow a directory structure from the file system Understand how a package is put into a JAR file.

The JAR utility copies a package from the file system into a JAR file A JAR file retains the directory structure from the file system

The manifest contains metadata and can specify location of 'main' method WHAT ARE PACKAGES?

A package is a collection of related classes.

This is similar to the notion that a class is a collection of related methods. Packages provide a mechanism for organizing large programs or code libraries.

Java code from a hard drive file system is organized within a package by a hierarchy that follows the pattern of the hard drive directory structure.

A package separates classes to ensure that class names are unique by making the package name part of fully qualified class names.

A package includes classes to allow a trust relationship between member classes.

Protected variables and methods may be accessed within a package without having to use getters and setters.

If you design a class as a reusable object, packages facilitate code reuse. HOW DO YOU USE A PACKAGE?

The Java platform is organized into libraries using packages and Java programmers use packages whenever they use the Java Development Kit (JDK).

For example, java.lang, java.util, java.io, and java.math are all packages. The java compiler automatically imports the java.lang package.

(2)

Import statements appear at the beginning of source code files so the compiler can build a qualified name for referenced classes.

Import a fully qualified specification of class and method.

import java.util.Scanner;

Import an entire package or a package subset.

import java.util.*;

Before a package is used, it must be found in the hard drive file system.

The Java compiler (javac.exe) and Java virtual machine (JVM) can find classes in the packages of the standard library, but need help locating user created packages and resolving naming conflicts.

The package search process starts at a root directory level called a classpath.

C:\greeter>set classpath

Environment variable classpath not defined

The following Java source program must import the classes in package greeter.entity without a classpath variable set in the environment.

// HelloWorld.java

import greeter.entity.*; public class HelloWorld {

public static void main(String[] args) { Entity entity = new Entity();

System.out.println("Hello," + entity.getName()); }

}

If a class from an imported package is not found in the current directory or on the classpath, an error is reported.

C:\greeter>javac HelloWorld.java

HelloWorld.java:1: package greeter.entity does not exist import greeter.entity.*;

^

HelloWorld.java:6: cannot find symbol symbol : class Entity

location: class HelloWorld

(3)

^

HelloWorld.java:6: cannot find symbol symbol : class Entity

location: class HelloWorld

Entity entity = new Entity(); ^

3 errors

The permanent classpath variable is set in the Windows registry, but a classpath variable that persists for the life of a command shell can be set in the environment and verified using the following commands.

C:\greeter>set classpath=.;C:\ C:\greeter>set classpath

classpath=.;C:\

The compiler and JVM will use this environment string to search first from the current directory and then from the root directory for an imported package’s classes.

Once found, the package’s class/method references are compiled as fully qualified specifications.

C:\greeter>javac Hello.java

The compiled program is loaded and run.

C:\greeter>java greeter.Hello Who is the greeting from? Bob Hello, World from Bob!

If the classpath is not set, it can be specified using a compiler and JVM command line option '-cp' and '-classpath'.

C:\greeter>javac -cp \ Hello.java C:\greeter>java -cp \ greeter.Hello Who is the greeting from?

Hello, World!

The compiler expands class references to fully qualified class and method names. When the program is run, the JVM class loader uses the fully qualified names to load classes and reports errors for classes it cannot find.

If the same class name appears in multiple imported packages, the compiler reports a name conflict error.

(4)

import java.util.*; import java.sql.*;

public class ImportConflict { Date today;

public static void main(String[] args) { System.out.println("Hello, World"); }

}

C:\greeter>javac ImportConflict.java

ImportConflict.java:5: reference to Date is ambiguous, both class java.sql.Date in java.sql and class java.util.Date in java.uti l match

Date today; ^

1 error

The naming conflict can be resolved by specifically importing one of the packaged classes by its fully qualified name.

// ImportConflictResolved.java import java.util.*;

import java.util.Date; import java.sql.*;

public class ImportConflictResolved { Date today;

public static void main(String[] args) { System.out.println("Hello, World"); }

}

If both conflicting class names are used, each must be fully qualified when referenced.

// FullyQualifiedRefs.java

public class FullyQualifiedRefs { java.util.Date today;

java.sql.Date tomorrow;

public static void main(String[] args) { System.out.println("Hello, World"); }

(5)

HOW IS A PACKAGE BUILT?

Classes are in a package when the source code file begins with a package statement. The package statement is first in the source code before package import statements. A class in a package can use other classes in the package. Methods and variables designated either public or protected are exposed to all classes within the package. Classes imported from other packages expose only public methods and variables.

// Hello.java package greeter;

import greeter.entity.*; public class Hello {

public static void main(String[] args) { String str = new String();

Salutation to = new Salutation(); Valediction from = new Valediction();

if (args.length > 0) { for (String s: args) { str = str + " " + s; } to.setName(str); } System.out.println(to.getName() + from.getName()); } }

Compiled java class files are placed into the directory structure of the computer file system below the classpath for the package.

The package statement is derived from the names in the directory structure that organizes source code and the compiled code.

In the examples, the Java Hello program is in package 'greeter' and imports classes from a package named 'greeter.entity'. Both of these packages are in a directory hierarchy that starts with the 'greeter' directory below the classpath at the root directory 'C:\'.

// Entity.java

package greeter.entity; public class Entity {

protected String entityName = " World";

(6)

return entityName; }

protected void setName(String entityName) { this.entityName = entityName;

} }

The Entity class protects its variable (entityName) and a method (setName). Outside of the package it is as if this variable and method are private.

// Salutation.java

package greeter.entity; public class Salutation {

private Entity to = new Entity(); public String getName() {

return "Hello," + to.entityName; }

public void setName(String entityName) { to.entityName = entityName;

} }

The Salutation class is a member of the same package as Entity, creates an instance of the Entity object, and directly sets the value of the variable 'to.entityName' in the object instance. An alternate approach would use the setName method of Entity. Both the variable and method are protected and accessible within the package.

// Valediction.java package greeter.entity; import java.util.Scanner; public class Valediction { public String getName() {

Scanner scan = new Scanner(System.in);

System.out.print("Who is the greeting from? "); String fromName = scan.nextLine();

if (fromName.length() > 0)

return " from " + fromName + "!"; else

(7)

} }

The Valediction class imports the Scanner class from the java.util package using the fully qualified class name in an import statement.

A recommended package naming convention is to reverse your email address and create a unique top level classpath for your applications and libraries.

For example, morrissettmr@vcu.edu is used to create a top level classpath of edu.vcu.morrissettmr using the hard drive directory \edu\vcu\morrissettmr\

This approach uses many levels in the directory, but guarantees unique package names. HOW IS A JAR FILE CREATED FROM A PACKAGE?

Java Archive (JAR) files use the ZIP file format.

The Java platform includes a JAR utility (jar.exe) that copies a package from the file system and puts the copy into a JAR file.

Packages in a JAR file retain the directory structure used to create the package. This makes the JAR a complete application or library in a single file.

The compiled Java runtime libraries are made available in rt.jar as a single JAR file. An optional manifest file located in the JAR as META-INF/MANIFEST.MF may be used by the JVM to locate the class containing method 'main' for an application. This allows a JAR file to be executable by the JVM.

[manifest.txt or file name of your choice] Main-Class: greeter.Hello

JAR files can be used to store and distribute packages.

jar cmvf manifest.txt hello.jar /greeter/Hello.class /greeter/entity/*.class added manifest

adding: greeter/Hello.class(in = 933) (out= 574)(deflated 38%)

adding: greeter/entity/Entity.class(in = 351) (out= 252)(deflated 28%) adding: greeter/entity/Salutation.class(in = 665) (out= 389)(deflated 41%) adding: greeter/entity/Valediction.class(in = 882) (out= 548)(deflated 37%)

Programs stored in JAR files can be run using the compiled packages and classes stored in the JAR directory structure as it was copied from the file system.

The classpath defaults to the top level of the JAR file structure.

C:\greeter>java -jar hello.jar Who is the greeting from?

(8)

Hello, World!

C:\greeter>java -jar hello.jar Moon Who is the greeting from? Bob

References

Related documents

Qualifying yarns for TACTEL® branded fabrics are available in the following Dtex counts: • Refer to NILIT Product Catalog. CHOICE OF

Rather like Denplan Essentials, this is a pretty flexible plan and can be set up by the dentist in a way that is best for his younger patients and how much dental care they

The study is helpful for many players in Home Appliances to make following strategies related to advertising for any particular company: -..  Advertising

1.3.4 The series compensation provides a means of regulating power flowing through two parallel lines by introducing series capacitance in one of the lines,

Life support systems are equipment intended to support or sustain life, and whose failure to perform, when properly used in accordance with instructions

He immediately after the signature requirement cannot give you are lost in document will give you how is a signature required for package delivery confirmation type selected

Given the restricted use of e-signatures to include internal use only and the requirement that all users must be authenticated to the Authority domain for an e-signature to be