Lecture 11 Packages
Lecture 11 Packages
Packages
Contact Info:
Room No: BS-04, CED
1 Email: ulaila@ssuet.edu.pk
Course Books
Text Book:
Herbert Schildt, Java: The Complete Reference, 12th
Edition ,McGraw-Hill Education.
Deitel, Paul, Java How to Program, 11th Edition, Pearson,
2017
Reference Books:
Horton, Ivor, Beginning Java, 7th Edition, Wrox, 2011
2
Course Instructors
Assignments + Quiz______________ 20
4
Recall the previous topic
Abstract Methods
An abstract class may contain abstract methods,
that is, methods with no implementation. In this
way, an abstract class can define a complete
programming interface, thereby providing its
subclasses with the method declarations for all of
the methods necessary to implement that
programming interface. However, the abstract class
can leave some or all of the implementation details
of those methods up to its subclasses.
Let's look at an example of when you might want to
create an abstract class with an abstract method in
it. In an object-oriented drawing application, you
can draw circles, rectangles, lines, Bezier curves,
and so on. Each of these graphic objects share
certain states (position, bounding box) and behavior
(move, resize, draw). You can take advantage of
these similarities and declare them all to inherit
from the same parent object--GraphicObject.
However, the graphic objects are also substantially
different in many ways: drawing a circle is quite
different from drawing a rectangle. The graphics
objects cannot share these types of states or
behavior. On the other hand, all GraphicObjects must
know how to draw themselves; they just differ in how
they are drawn. This is a perfect situation for an
abstract superclass.
First you would declare an abstract class, GraphicObject, to
provide member variables and methods that were wholly
shared by all subclasses, such as the current position and
the moveTo method.
13
Package concept
• A Package is a logical grouping of classes
– Primarily to a void name clashes
– Identifies where the class code can be found
com.qatraining.cad.vehicle
Engine Truck
Car Gearbox
Engine.class
com vehicle
cad Truck.class
qatraining
Gearbox.class
Referring to classes in a
package
The name of a class includes its package, and can be quite
long
edu.purdue.tech.vehicle.Car car1; -
vehicle.Car car1;
Car car1;
Import Statement
To avoid typing fully qualified names – use
import statements sandwiched between the
package statement and class definition.
The import statement allows you to use short
class names
import statements enable abbreviated names
to be used
Import must be placed before the first class
description
If a class has to import two packages, their full
names must be used to disambiguate them
The package java.lang is imported implicitly,
therefore any of its classes can be used
without qualification
Types of packages in
Java
we have two types of packages in java.
1.User defined package: The package we create is called user-defined
package.
18
Using System Packages
The packages are organised in a
hierarchical structure. For example, a
package named “java” contains the
package “awt”, which in turn contains
various classes required for
implementing GUI (graphical user
java
interface).
lang
“java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt
Graphics
awt Package containing
Font classes
19 …
Accessing Classes from Packages
import package.class;
Implicit in all programs: import java.lang.*;
packageimport package.*;
statement(s) must appear first
20
2.User Defined Packages:
Creating Packages
Java supports a keyword called
“package” for creating user-
defined packages. The package statement must be the
first statement in a Java source file (except comments
and white spaces) followed by one or more classes.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
Package // class is
name body
“myPackage”
and classes are
}
considered as part of this package; The code is saved
in a file called “ClassA.java” and located in a directory
called “myPackage”.
21
Creating Sub Packages
Classes in one ore more source files can be part of
the same packages.
As packages in Java are organised
hierarchically, sub-packages can be
created as follows:
package myPackage.Math
package myPackage.secondPakage.thirdPackage
Store “thirdPackage” in a subdirectory named
“myPackage\secondPackage”. Store
“secondPackage” and “Math” class in a
subdirectory “myPackage”.
22
Accessing a Package
As indicated earlier, classes in packages
can be accessed using a fully qualified
name or using a short-cut as long as we
import a corresponding package.
The general form of importing package is:
import package1[.package2][…].classname
Example:
import myPackage.ClassA;
import myPackage.secondPackage
All classes/packages from higher-level package
can be imported as follows:
import myPackage.*;
23
Using a Package
Let us store the code listing below in a
file named “ClassA.java” within
subdirectory named “myPackage”
within the current directory (say “abc”).
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am
ClassA");
}
}
class ClassB {
// class body}
24
Using a Package
import myPackage.ClassA;
25
Compiling and Running
When ClassX.java is compiled, the
compiler compiles it and places .class
file in current directly. If .class of ClassA
in subdirectory “myPackage” is not
found, it comples ClassA also.
Note: It does not include code of ClassA
into ClassX
When the program ClassX is run, java
loader looks for ClassA.class file in a
package called “myPackage” and loads
it.
26
Using a Package
import myPackage.ClassA;
import secondPackage.ClassC;
public class ClassY
{
public static void main(String args[])
{
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
28
Example of Package
As we know packages are used to
avoid conflicts of having same class
names.
In this example. There are two
packages which have same class
name Leaf.
Example of Package
File SearchTree/Leaf
package SearchTree;
public class Leaf
{ public Leaf()
{System.out.println( "Leaf in a binary search tree" );}
}
File Botany/Leaf
package Botany;
public class Leaf
{ public Leaf()
{ System.out.println( "Leaf in a real tree" );}}
In order to access the Leaf class we have
two options.
1.Use the full name of each class to avoid
conflict
class Test
{
public static void main( String args[] )
{
Botany.Leaf green = new Botany.Leaf();
SearchTree.Leaf node = new SearchTree.Leaf();
}
}
2. Import one class and use the
full name of the other class
import SearchTree.Leaf;
class Test
{
public static void main( String args[] )
{
Botany.Leaf green = new Botany.Leaf();
Leaf node = new Leaf();
}
}
Import both packages on demand to import
other classes in each package and use the
full name for the Leaf classes
Importing Both Leaf Classes - Error
import SearchTree.Leaf;
import Botany.Leaf; // Compile error
class Test
{
public static void main( String args[] )
{
Botany.Leaf green = new Botany.Leaf();
Leaf node = new Leaf();}
}
Import on demand
What should this do? And
Why?
import SearchTree.Leaf;
import Botany.*;
class Test
{
public static void main( String args[] )
{
Botany.Leaf green = new Botany.Leaf();
Leaf node = new Leaf();}
}
Import on demand
36
Visibility - Revisited
Public keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
Private fields or methods for a class only
visible within that class. Private members
are not visible within subclasses, and are not
inherited.
Protected members of a class are visible
within the class, subclasses and also within
all classes that are in the same package as
that class.
37
Visibility Modifiers
Non-subclass Yes No No No
different package
38
Adding a Class to a Package
Consider an existing package that contains
a class called “Teacher”:
package pack1;
public class Teacher
{
// class
This class body
is stored in “Teacher.java” file
within }
a directory called “pack1”.
How do we a new public class called
“Student” to this package.
39
Adding a Class to a Package
Define the public class “Student” and place the
package statement before the class definition as
follows:
40
Packages and Name Clashing
When packages are developed by different
organizations, it is possible that multiple
packages will have classes with the same name,
leading to name classing.
41
Handling Name Clashing
In Java, name classing is resolved by
accessing classes with the same name in
multiple packages by their fully qualified
name.
Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;
42
Extending a Class from Package
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}
43
Static Imports
Static import means that the fields and
methods in a class can be used in the code
without specifying their class if they are
defined as public static.
Static import allows you to access the
static member of a class directly without
using the fully qualified name.
Static imports are used for saving your
time by making you type less. If you hate
to type same thing again and again then
you may find such imports interesting.
Example of static Import
With out static import With static import
class Demo1{ import static java.lang.System.out;
public static void main(String import static java.lang.Math.*;
args[]) class Demo2{
{ public static void main(String args[])
double var1= Math.sqrt(5.0); {
//instead of Math.sqrt need to use only sqrt
double var2= Math.tan(30);
double var1= sqrt(5.0);
System.out.println("Square of 5
is:"+ var1); //instead of Math.tan need to use only tan
double var2= tan(30);
System.out.println("Tan of 30
is:"+ var2); //need not to use System in both the below
statements
}
out.println("Square of 5 is:"+var1);
} out.println("Tan of 30 is:"+var2);
}}
When to use static imports?
If you are going to use static variables and
methods a lot then it’s fine to use static
imports. for example if you wanna write a
code with lot of mathematical calculations
then you may want to use static import.
Drawbacks
It makes the code confusing and less readable
so if you are going to use static members very
few times in your code then probably you
should avoid using it. You can also use
wildcard(*) imports.
Summary
47