[go: up one dir, main page]

0% found this document useful (0 votes)
65 views18 pages

Unit 9: Packages and Interface: Package

The document discusses Java packages, including defining packages, package hierarchies, finding packages, access protection, and importing packages. Packages are used to organize classes and interfaces, provide access control, and avoid naming collisions. The CLASSPATH variable and -classpath option can be used to locate packages.

Uploaded by

mahdy.00523775
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views18 pages

Unit 9: Packages and Interface: Package

The document discusses Java packages, including defining packages, package hierarchies, finding packages, access protection, and importing packages. Packages are used to organize classes and interfaces, provide access control, and avoid naming collisions. The CLASSPATH variable and -classpath option can be used to locate packages.

Uploaded by

mahdy.00523775
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

https://genuinenotes.

com
Unit-9 / Java Programming - I

Unit 9: Packages and Interface


 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

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

1 Collected by Bipin Timalsina

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.

2 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

Finding Packages and CLASSPATH


As just explained, packages are mirrored by directories. This raises an important question: How
does the Java run-time system know where to look for packages that you create? The 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.
For example, consider the following package specification:
Package MyPack
In order for a program to find MyPack, one of three things must be true. Either 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

then the class path to MyPack is

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.

3 Collected by Bipin Timalsina

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.

4 Collected by Bipin Timalsina

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();

5 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

}
}
Output:
Hello

2. To import only the class/classes you want to use


If you import packagename.classname then only the class with name classname in the package
with name packagename will be available for use.
Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("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

6 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

3. To import all the classes from a particular package


If you use packagename.*, then all the classes and interfaces of this package will be accessible
but the classes and interface inside the subpackages will not be available for use.
The import keyword is used to make the classes and interface of another package accessible to
the current package.

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

7 Collected by Bipin Timalsina

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.*;

8 Collected by Bipin Timalsina

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.

 Beginning with JDK 8, it is possible to add a default implementation to an interface


method. Also, static methods are supported in interface.

9 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

An interface is similar to a class in the following ways −


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
 We cannot instantiate an interface (i.e. object cannot be created ).
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
Note : As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Interfaces have the following properties −


 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.
Interface fields are public, static and final by default, and the methods are public and abstract.

10 Collected by Bipin Timalsina

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

// implement required methods


[modifiers] returnType methodName1(arguments) {
//executable code
}

//any other desired methods

 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.

11 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}
}

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:

12 Collected by Bipin Timalsina

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.

13 Collected by Bipin Timalsina

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 :

14 Collected by Bipin Timalsina

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:

15 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

System.out.println(" Go South");
break;
default:
System.out.println("Invalid choice!");
break;
}
}
}

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.
Following is an example:

16 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-9 / Java Programming - I

17 Collected by Bipin Timalsina

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");}

public static void main(String args[]){


Test obj = new Test();
obj.print();
obj.show();
}
}

18 Collected by Bipin Timalsina

https://genuinenotes.com

You might also like