Unit 9: Packages and Interface: Package
Unit 9: Packages and Interface: Package
com
Unit-9 / Java Programming - I
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. You can also define class
members that are exposed only to other members of the same package. This allows your classes
to have intimate knowledge of each other, but not expose that knowledge to the rest of the world.
Advantage of Java Package
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
protected and default have package level access control. A protected member is
accessible by classes in the same package and its subclasses. A default member (without
any access specifier) is accessible by classes in the same package only.
Java package removes naming collision (namespace management)
For example there can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Defining a Package
The package keyword is used to create a package in java.
The package statement defines a name space in which classes are stored.
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package, which has no name.
To compile the Java programs with package statements, you have to use -d option as
shown below.
javac -d Destination_folder file_name.java
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;
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.
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 java.awt.image needs to be stored in
java\awt\image 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.
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
CLASSPATH is actually an environment variable in Java, and tells Java applications and the
Java Virtual Machine (JVM) where to find the libraries of classes. These include any that you
have developed on your own.
An environment variable is a global system variable, accessible by the computer's operating
system (e.g., Windows). Other variables include COMPUTERNAME, USERNAME (computer's
name and user name).
In Java, CLASSPATH holds the list of Java class file directories, and the JAR file, which is
Java's delivered class library file.
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Access Protection
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.
Classes act as containers for data and code. The class is Java’s smallest unit of abstraction.
Because of the interplay between classes and 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
Anything declared public can be accessed from anywhere in the project.
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.
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Importing Packages
There are three ways to access the package from outside the package.
1. fully qualified name.
2. import packagename.classname
3. import packagename.*;
import keyword is used to import built-in and user-defined packages into your java
source file so that your class can refer to a class that is in another package by directly
using its name.
There are 3 different ways to refer to any class that is present in a different package:
1. Using fully qualified name
If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the
same package will not be accessible. For this approach, there is no need to use
the import statement. But you will have to use the fully qualified name every time you
are accessing the class or the interface, which can look a little untidy if the package name
is long.
This is generally used when two packages have classes with same names. For
example: java.util and java.sql packages contain Date class.
Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
}
}
Output:
Hello
//save by B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output:
Hello
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Example :
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}
//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}
Output:
Hello
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
NOTES:
A package inside another package is known as sub package.
A file can have only a package declaration but can have multiple import statements.
While creating a package, care should be taken that the statement for creating package
must be written before any other import statements.
// not allowed
import package p1.*;
package p3;
Below code is correct, while the code mentioned above is incorrect.
//correct syntax
package p3;
import package p1.*;
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Interfaces
An interface is a reference type in Java. It is similar to class
An interface in java is a blueprint of a class. It has static constants and abstract methods.
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 specify what a class must do and not how.
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.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
Syntax:
[modifiers] interface InterfaceName {
// declaring methods
[public abstract] returnType methodName1(arguments);
// defining constants
[public static final] type fieldName = value;
}
The access level for the entire interface is usually public. It may be omitted, in which
case the interface is only available to other classes in the same package (i.e. default
access).Note, for the sake of completeness, and there are situations where the interface
definition could be protected or private; these involve what are called inner classes.
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then
create the methods required by the interface.
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all
the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface
Syntax:
[modifiers] class ClassName implements InterfaceName {
//any desired fields
If a class implements more than one interface, the interfaces are separated with a comma.
If a class Tyre is implementing two interfaces Moveable and Rollable then
class Tyre implements Moveable, Rollable
{
. . . .
}
It is both permissible and common for classes that implement interfaces to define
additional members of their own.
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
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.
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.
Here is an example that demonstrates a nested interface:
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Notice that A defines a member interface called NestedIF and that it is declared public. Next, B
implements the nested interface by specifying
Notice that the name is fully qualified by the enclosing class’ name. Inside the main( ) method,
an A.NestedIF reference called nif is created, and it is assigned a reference to a B object.
Because B implements A.NestedIF, this is legal.
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Applying Interfaces
Another Example:
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class NMB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Variables in Interfaces
You can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. When you include that
interface in a class (that is, when you “implement” the interface), all of those variable names will
be in scope as constants. (This is similar to using a header file in C/C++ to create a large number
of #defined constants or const declarations.) If an interface contains no methods, then any class
that includes such an interface doesn’t actually implement anything. It is as if that class were
importing the constant fields into the class name space as final variables.
All variables declared inside interface are implicitly public static final variables (constants).
Example :
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
//File: SharedConstants.java
package examples;
public interface SharedConstants {
int EAST=0;
int WEST=1;
int NORTH=2;
int SOUTH=3;
}
………………………………………………………………………
//File: InterfaceVariableTest.java
package examples;
import java.util.Scanner;
public class InterfaceVariableTest implements SharedConstants{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number from 0 to 3");
int n = sc.nextInt();
switch (n) {
case EAST:
System.out.println("Go East");
break;
case WEST:
System.out.println("Go West");
break;
case NORTH:
System.out.println("Go North");
break;
case SOUTH:
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
System.out.println(" Go South");
break;
default:
System.out.println("Invalid choice!");
break;
}
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I
Multiple inheritance is not supported through class in java, but it can be achieved using
interfaces
interface Printable{
void print();
}
interface Showable{
void show();
}
class Test implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
https://genuinenotes.com