0% found this document useful (0 votes)
12 views

Packages and Interfaces in Java

Packages in Java allow organizing classes into groups to avoid naming collisions. A package is defined using the package keyword and classes within that file will belong to that package. Packages can be organized hierarchically and must be reflected in the file system. The import statement allows bringing classes from other packages into visibility without needing the fully qualified class name.

Uploaded by

gourilakshmis78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Packages and Interfaces in Java

Packages in Java allow organizing classes into groups to avoid naming collisions. A package is defined using the package keyword and classes within that file will belong to that package. Packages can be organized hierarchically and must be reflected in the file system. The import statement allows bringing classes from other packages into visibility without needing the fully qualified class name.

Uploaded by

gourilakshmis78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Packages in Java

Package

◼ Packages are containers for classes.


◼ used to keep the class name space compartmentalized.
◼ Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions
◼ so far, the name of each example class was taken from the same
name space
◼ means that a unique name had to be used for each class to avoid
name collisions
◼ Java provides a mechanism for partitioning the class name space
into more manageable chunks
◼ This mechanism is the package.
◼ The package is both a naming and a visibility control mechanism.
◼ You can define classes inside a package that are not accessible by
code outside that package. 2
Defining a Package
◼ include a package command as the first statement in a Java source file
◼ Any classes declared within that file will belong to the specified package
◼ The package statement defines a name space in which classes are stored
◼ If you omit the package statement, the class names are put into the
default package, which has no name
◼ default package is fine for short, sample programs, it is inadequate for
real applications
◼ Most of the time, you will define a package for your code
◼ This is the general form of the package statement:
package pkg;
◼ Here, pkg is the name of the package.
◼ For example, the following statement creates a package called
mypackage:
package mypackage;
3
Defining a Package
◼ Java uses file system directories to store packages.
◼ For example, the .class files for any classes you declare to be part of
mypackage must be stored in a directory called mypackage.
◼ Remember that case is significant, and the directory name must match the
package name exactly.
◼ More than one file can include the same package statement.
◼ The package statement simply specifies to which package the classes
defined in a file belong.
◼ It does not exclude other classes in other files from being part of that
same package.
◼ Most real-world packages are spread across many files.

4
Defining hierarchy of packages
◼ You can create a hierarchy of packages.
◼ To do so, simply separate each package name from the one above it by
use of a period.
◼ The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
◼ A package hierarchy must be reflected in the file system of your Java
development system.
◼ For example, a package declared as
package a.b.c;
◼ needs to be stored in a\b\c in a Windows environment.
◼ Be sure to choose your package names carefully.
◼ You cannot rename a package without renaming the directory in which
the classes are stored.

5
Finding Packages and CLASSPATH
◼ packages are typically mirrored by directories.
◼ This raises an important question: How does the Java run-time
system know where to look for packages that you create?
◼ answer has three parts.
◼ First, by default, the Java run-time system uses the current working
directory as its starting point.
◼ Thus, if your package is in a subdirectory of the current directory,
it will be found.
◼ Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
◼ Third, you can use the -classpath option with java and javac to
specify the path to your classes.

6
Finding Packages and CLASSPATH
◼ For example, consider the following package specification:
package mypack;
◼ In order for a program to find mypack, the program can be executed from a
directory immediately above mypack,
◼ or the CLASSPATH must be set to include the path to mypack, or the -classpath
option must specify the path to mypack when the program is run via java.
◼ When the second two options are used, the class path must not include mypack,
itself. It must simply specify the path to mypack.
◼ For example, in a Windows environment, if the path to mypack is
C:\MyPrograms\Java\mypack
◼ then the class path to mypack is
C:\MyPrograms\Java
◼ The easiest way to try the examples is to simply create the package directories
below your current development directory, put the .class files into the
appropriate directories, and then execute the programs from the development
directory.
7
Package Example

8
Packages and Member Access
◼ Packages add another dimension to access control.
◼ Java provides many levels of protection to allow fine-grained control over the
visibility of variables and methods within classes, subclasses, and packages.
◼ Classes and packages are both means of encapsulating and containing the name
space and scope of variables and methods.
◼ Packages act as containers for classes and other subordinate packages. \
◼ Java addresses four categories of visibility for class members:
◼ • Subclasses in the same package
◼ • Non-subclasses in the same package
◼ • Subclasses in different packages
◼ • Classes that are neither in the same package nor subclasses

Access rules applies only to members of classes


9
Packages and Member Access
◼ Anything declared public can be accessed from different classes and different
packages.
◼ Anything declared private cannot be seen outside of its class.
◼ When a member does not have an explicit access specification, it is visible to
subclasses as well as to other classes in the same package. This is the default
access.
◼ If you want to allow an element to be seen outside your current package, but
only to classes that subclass your class directly, then declare that element
protected
◼ A non-nested class has only two possible access levels: default and public.
◼ When a class is declared as public, it is accessible outside its package.
◼ If a class has default access, then it can only be accessed by other code within its
same package.
◼ When a class is public, it must be the only public class declared in the file, and
the file must have the same name as the class.

10
Packages and Member Access

11
Packages and Member Access

12
Packages and Member Access

13
Packages and Member Access

14
Packages and Member Access

15
Importing Packages
◼ why all of the built-in Java classes are stored in packages.
◼ There are no core Java classes in the unnamed default package; all of the
standard classes are stored in some named package.
◼ Since classes within packages must be fully qualified with their package name or
names, it could become tedious to type in the long dot-separated package path
name for every class you want to use.
◼ For this reason, Java includes the import statement to bring certain classes, or
entire packages, into visibility.
◼ Once imported, a class can be referred to directly, using only its name.
◼ In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
◼ This is the general form of the import statement:
import pkg1 [.pkg2].(classname | *);
◼ Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
◼ There is no practical limit on the depth of a package hierarchy, except that
imposed by the file system.
16
Importing Packages
◼ All of the standard Java SE classes included with Java begin with the name java.
◼ The basic language functions are stored in a package called java.lang.
◼ Normally, you have to import every package or class that you want to use, but
since Java is useless without much of the functionality in java.lang, it is
implicitly imported by the compiler for all programs.
◼ This is equivalent to the following line being at the top of all of your programs:
import java.lang.*;
◼ If a class with the same name exists in two different packages that you import
using the star form, the compiler will remain silent, unless you try to use one of
the classes.
◼ In that case, you will get a compile-time error and have to explicitly name the
class specifying its package.

17
Importing Packages
◼ It must be emphasized that the import statement is optional.
◼ Any place you use a class name, you can use its fully qualified name, which
includes its full package hierarchy.
◼ For example, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date {
}
◼ The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}

18
Importing Packages

19
Importing Packages

20
Interfaces
◼ Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
◼ That is, using interface, you can specify what a class must do, but not how it
does it.
◼ Interfaces are syntactically similar to classes, but they lack instance variables,
and, as a general rule, their methods are declared without any body.
◼ In practice, this means that you can define interfaces that don’t make
assumptions about how they are implemented.
◼ Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces.
◼ To implement an interface, a class must provide the complete set of methods
required by the interface.
◼ However, each class is free to determine the details of its own implementation.
◼ By providing the interface keyword, Java allows you to fully utilize the “one
interface, multiple methods” aspect of polymorphism.

21
Interfaces
◼ Interfaces are designed to support dynamic method resolution at run time.
◼ Normally, in order for a method to be called from one class to another, both
classes need to be present at compile time so the Java compiler can check to
ensure that the method signatures are compatible.
◼ This requirement by itself makes for a static and nonextensible classing
environment.
◼ Inevitably in a system like this, functionality gets pushed up higher and higher in
the class hierarchy so that the mechanisms will be available to more and more
subclasses.
◼ Interfaces are designed to avoid this problem.
◼ They disconnect the definition of a method or set of methods from the
inheritance hierarchy.
◼ Since interfaces are in a different hierarchy from classes, it is possible for classes
that are unrelated in terms of the class hierarchy to implement the same interface.
◼ This is where the real power of interfaces is realized.

22
Defining an Interface
They are implicitly final
and static, meaning they
cannot be changed by the
implementing class.
They must also be
initialized. All methods
and variables are
implicitly public.

◼ no access modifier, then available to other members of the same package.


◼ public, the interface can be used by code outside its package.
◼ Notice that the methods that are declared have no bodies.
◼ They end with a semicolon after the parameter list.
◼ They are, essentially, abstract methods.
◼ Each class that includes such an interface must implement all of the methods.
◼ Prior to JDK 8, an interface could not define any implementation
◼ Beginning with JDK 8, it is possible to add a default implementation to an
interface method, also added static interface methods, and beginning with JDK 9,
an interface can include private methods
23
Implementing Interfaces
◼ To implement an interface, include the implements clause in a class definition,
and then create the methods required by the interface.
◼ The general form of a class that includes the implements clause looks like this:

◼ If a class implements more than one interface, the interfaces are separated with a
comma.
◼ If a class implements two interfaces that declare the same method, then the same
method will be used by clients of either interface.
◼ The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.

24
Implementing Interfaces
◼ It is both permissible and common for classes that implement interfaces to define
additional members of their own.

25
Accessing Implementations Through
Interface References
◼ You can declare variables as object references that use an interface rather than a
class type.
◼ Any instance of any class that implements the declared interface can be referred
to by such a variable.
◼ When you call a method through one of these references, the correct version will
be called based on the actual instance of the interface being referred to.
◼ This is one of the key features of interfaces.
◼ The method to be executed is looked up dynamically at run time, allowing
classes to be created later than the code which calls methods on them.
◼ The calling code can dispatch through an interface without having to know
anything about the “callee.”
◼ This process is similar to using a superclass reference to access a subclass object

26
Accessing Implementations Through
Interface References

27
Partial Implementations
◼ If a class includes an interface but does not fully implement the methods required
by that interface, then that class must be declared as abstract.

◼ Here, the class Incomplete does not implement callback( ) and must be declared
as abstract.
◼ Any class that inherits Incomplete must implement callback( ) or be declared
abstract itself.

28
Nested Interfaces
◼ An interface can be declared a member of a class or another interface.
◼ Such an interface is called a member interface or a nested interface.
◼ A nested interface can be declared as public, private, or protected.
◼ This differs from a top-level interface, which must either be declared as public or
use the default access level, as previously described.
◼ When a nested interface is used outside of its enclosing scope, it must be
qualified by the name of the class or interface of which it is a member.
◼ Thus, outside of the class or interface in which a nested interface is declared, its
name must be fully qualified.

29
Nested Interfaces

30
Interfaces Can Be Extended
◼ One interface can inherit another by use of the keyword extends.
◼ The syntax is the same as for inheriting classes.
◼ When a class implements an interface that inherits another interface, it must
provide implementations for all methods required by the interface inheritance
chain

31
Interfaces Can Be Extended

32
Default Interface Methods
◼ A default method lets you define a default implementation for an interface
method.
◼ In other words, by use of a default method, it is possible for an interface method
to provide a body, rather than being abstract
◼ A primary motivation for the default method was to provide a means by which
interfaces could be expanded without breaking existing code.
◼ Recall that there must be implementations for all methods defined by an
interface.
◼ In the past, if a new method were added to a popular, widely used interface, then
the addition of that method would break existing code because no
implementation would be found for that new method.
◼ The default method solves this problem by supplying an implementation that will
be used if no other implementation is explicitly provided

33
Default Method Fundamentals
◼ An interface default method is defined similar to the way a method is defined by
a class.
◼ The primary difference is that the declaration is preceded by the keyword
default.

34
Default Method Fundamentals
◼ An interface default method is defined similar to the way a method is defined by
a class.
◼ The primary difference is that the declaration is preceded by the keyword
default.

◼ It is possible to explicitly refer to a default implementation in an inherited


interface by using this form of super. Its general form is shown here:
InterfaceName.super.methodName( )
35
Use static Methods in an Interface
◼ Another capability added to interface by JDK 8 is the ability to define one or
more static methods.
◼ Like static methods in a class, a static method defined by an interface can be
called independently of any object.
◼ Thus, no implementation of the interface is necessary, and no instance of the
interface is required, in order to call a static method.
◼ Instead, a static method is called by specifying the interface name, followed by a
period, followed by the method name.
◼ Here is the general form:
InterfaceName.staticMethodName

36
Use static Methods in an Interface

37
Private Interface Methods
◼ Beginning with JDK 9, an interface can include a private method.
◼ A private interface method can be called only by a default method or another
private method defined by the same interface.
◼ Because a private interface method is specified private, it cannot be used by code
outside the interface in which it is defined.
◼ This restriction includes subinterfaces because a private interface method is not
inherited by a subinterface.
◼ The key benefit of a private interface method is that it lets two or more default
methods use a common piece of code, thus avoiding code duplication.

38

You might also like