[go: up one dir, main page]

0% found this document useful (0 votes)
15 views47 pages

Lecture 11 Packages

oop

Uploaded by

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

Lecture 11 Packages

oop

Uploaded by

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

Lecture#10

Packages

Course: Object oriented Programming (CE-205)


Course Teacher: Dr Umm-e-Laila& Ms.Aneeta
Siddiqui

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

 Dr. Umm-e-Laila ulaila@ssuet.edu.pk


Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536

 Aneeta Siddiqui aarshad@ssuet.edu.pk


Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Marks Distribution

Assignments + Quiz______________ 20

Mid Term ______________ 30

Semester Final Paper ______________ 50

Total Marks ______________ 100

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.

 GraphicObject also declares abstract methods for methods,


such as draw, that need to be implemented by all
subclasses, but are implemented in entirely different ways
(no default implementation in the superclass makes sense).

 The GraphicObject class would look something like this:


abstract class GraphicObject {
int x, y; . . .
Void moveTo(int newX, int newY) { ... }
abstract void draw();}
 Each non-abstract subclass of GraphicObject, such
as Circle and Rectangle, would have to provide an
implementation for the draw method.

class Circle extends GraphicObject {


void draw() { . . . }}
class Rectangle extends GraphicObject {
void draw() { . . . }}

 An abstract class is not required to have an


abstract method in it. But any class that has an
abstract method in it or that does not provide an
implementation for any abstract methods
declared in its superclasses must be declared as
an abstract class.
review

 Based on the GeometricObject -> Circle -> Cylinder


hierarchy from last class, which of these are legal?
GeometricObject g = new Circle();
Circle circle = new Circle();
Cylinder cylinder = new Circle();
 What is the purpose of an abstract class?
 If you write a class to extend an abstract class, what
must you do? There are two possible answers to this
question.
Packages
Packages
 Packages are Java’s way of grouping a number of
related classes and/or interfaces together into a
single unit. That means, packages act as
“containers” for classes.
 The benefits of organising classes into packages
are:
 The classes contained in the packages of other
programs/applications can be reused.
 In packages classes can be unique compared with classes
in other packages. That two classes in two different
packages can have the same name. If there is a naming
clash, then classes can be accessed with their fully
qualified name.
 Classes in packages can be hidden if we don’t want other
packages to access them.
 Packages also provide a way for separating “design” from
coding.

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

• Packages are organised hierarchically


– Maps to a hierarchical directory structure
– May map to an Internet domain Car.class

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.

2. Built-in package: The already defined package like java.io.*,


java.lang.* etc are known as built-in packages.
1.Built In Packages :Java
Foundation Packages
 Java provides a large number of classes groped into different
packages based on their functionality.
 The six foundation Java packages are:
 java.lang
 Contains classes for primitive types, strings, math functions, threads,
and exception
 java.util
 Contains classes such as vectors, hash tables, date etc.
 java.io
 Stream classes for I/O
 java.awt
 Classes for implementing GUI – windows, buttons, menus etc.
 java.net
 Classes for networking
 java.applet
 Classes for creating and implementing applets

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

Image Classes containing


methods

19 …
Accessing Classes from Packages

 There are two ways of accessing the classes stored in


packages:
 Using fully qualified class name
 java.lang.Math.sqrt(x);
 Import package and use class name directly.
 import java.lang.Math
 Math.sqrt(x);
 Selected or all classes in packages can be imported:

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

 Within the current directory (“abc”) store the


following code in a file named “ClassX.java”

import myPackage.ClassA;

public class ClassX


{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}

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

 Let us store the code listing below in a


file named “ClassA.java” within
subdirectory named “secondPackage”
within the current directory (say “abc”).
package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I
am ClassC");
}
}
27
Using a Package
 Within the current directory (“abc”) store the
following code in a file named “ClassX.java”

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

 You can replace the class name in the import


statement with an "*".
 This will import all classes in that package and is
called import on demand
 The following import statement will import all classes
in the EDU.sdsu.roger package
 import EDU.sdsu.roger.*;
Protection and Packages
 All classes (or interfaces) accessible to all
others in the same package.
 Class declared public in one package is
accessible within another. Non-public class is
not
 Members of a class are accessible from a
difference class, as long as they are not
private
 protected members of a class in a package
are accessible to subclasses in a different
class

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

Accessible to: public protected Package private


(default)

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass in Yes Yes No No


different package

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:

package pack1; package pack1 ;


public class Student
{ class Teacher
 // class body
Store this in “Student.java” file underclass Student
the directory
}
“pack1”.
 When the “Student.java” file is compiled, the class
file will be created and stored in the directory
“pack1”. Now, the package “pack1” will contain
both the classes “Teacher” and “Student”.

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.

package pack1 ; package pack2 ;


class
 We can Teacher class Student
import and use these packages like:
 import pack1.*;
class Student
 import pack2.*;
class Courses
 Student student1; // Generates compilation error

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

 A new class called “Professor” can be created by


extending the “Teacher” class defined the package
“pack1” as follows:

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

 Packages allow grouping of related classes into a


single united.
 Packages are organised in hierarchical structure.
 Packages handle name classing issues.
 Packages can be accessed or inherited without
actual copy of code to each program.

47

You might also like