Packages - University of Surrey

advertisement
Programming Languages 2 - week 7
Slide set B –
Packages
http://www.computing.surrey.ac.uk/personal/st/D.Bish
Packages
Revision Æ
Æ
Æ
Packages Æ
Æ
Æ
directoriesÆ
Slide 1
system classes organised as packages
java.lang, java.util
.class files
what are they?
how created?
how used?
relation of packages to directories
CLASSPATHÆ how to use it
example Æ
programs
©David Bish, Dept of Computing, Univ of Surrey
ion In PL1, Wk 10 (in the notes) we said: Slide 3
revis
By default, each use of a system-provided
class should state the package name and
class name as well as the method name.
E.g. z = java.lang.Math.sqrt (5.1);
package class
method
name name
name
an import statement allows omission of
package name. E.g. given import java.lang.*;
we
also we may just type z = Math.sqrt (5.1);
said
now no
package name
statement import java.lang.*; is always
but the
we assumed (by the compiler).
said
©David Bish, Dept of Computing, Univ of Surrey
revision
Slide 5
PL2, wk 2 slide set B, sl 2 & 3
• Classes can be spread over multiple source files.
• Compilation always yields separate bytecode files.
• Only one class in a file can be public.
• A public class dictates source file name.
class Fred
In PL1, Wk 10 we said:
public class Fred
only
{
Fred is
public static void main (String [ ] args)
public
{
int age = 20;
System.out.println ("Fred's age is " + age);
Jo.ageOfJo ( );
}
}
Two classes - just
class Jo
one source file
{
static void ageOfJo ( )
{
int age = 21;
Jo not
System.out.println ("Jo's age is " + age);
}
public
} ©David Bish, Dept of Computing, Univ of Surrey
Slide 2
Classes are grouped
together into packages.
then we were
only interested
the Math class
Math
class
we noted other
packages
containing
classes and
methods
java.lang
package
individual
methods
String
Class
we get a feel for a simple use
of packages
http://www.computing.surrey.ac.uk/personal/st/D.Bish
class Jo
n
revisio
e.g. java.util package
methods
handling
strings
©David Bish, Dept of Computing, Univ of Surrey
AND AGAIN in PL1,
Wk 10 (in the triangle
program) we said:
*
***
*****
*******
*********
Slide 4
revision
“Since Scanner is a class
in the package java.util,
this import statement
allows us to type
import java.util.*;
public class Triangle
Scanner sc = new
{
Scanner (System.in);
public static void
main (String [ ] args)
{
instead of having to type
int n,h;
Scanner sc = new
sc
Scanner (System.in); java.util.Scanner
= new java.util.Scanner
.
(System.in);”
.
©David Bish, Dept of Computing, Univ of Surrey
C:\demo>javac Fred.java
C:\demo>dir
Volume in drive C has no label.
Volume Serial Number is 30AD-CC15
Directory of C:\demo
17/01/2007 14:45 <DIR>
.
17/01/2007 14:45 <DIR>
..
17/01/2007 15:23
661 Fred.class
17/01/2007 15:23
308 Fred.java
17/01/2007 15:23
600 Jo.class
3 File(s)
1,569 bytes
2 Dir(s) 23,905,132,544 bytes free
C:\demo>java Fred
Fred's age is 20
Jo's age is 21
C:\demo>
revision Slide 6
Output
separate
bytecode file
created for
each of the
two classes
bytecode
in file
Fred.class
successfully
calls bytecode
method
ageOfJo ( )
in file Jo.class
©David Bish, Dept of Computing, Univ of Surrey
©David Bish, Dept of Computing, University of Surrey – Spring Semester, 2008
Programming Languages 2 - week 7
Slide set B –
Packages
http://www.computing.surrey.ac.uk/personal/st/D.Bish
Slide 7
Same
Program Now two classes / two source files
revision
public class Fred
{
public static void main (String [ ] args)
now only
{
the public
int age = 20;
class Fred
System.out.println
is in file
("Fred's age is " + age);
Jo.ageOfJo ( );
Fred.java
}
}
class Jo
{
static void ageOfJo ( )
{
int age = 21;
System.out.println
("Jo's age is " + age);
}
}
class Jo (only) is
now in file named
David.java – the file
must be a ‘.java’ file
but need not be
named Jo since Jo
is not a public class
C:\demo>javac Fred.java
C:\demo>javac David.java
C:\demo>dir
Volume in drive C has no label.
Volume Serial Number is 30AD-CC15
Directory of C:\demo
17/01/2007 17:56 <DIR>
.
17/01/2007 17:56 <DIR>
..
17/01/2007 17:56
139 David.java
17/01/2007 17:55
661 Fred.class
17/01/2007 17:55
187 Fred.java
17/01/2007 17:56
601 Jo.class
4 File(s)
1,588 bytes
2 Dir(s) 23,905,075,200 bytes free
source code
file
David.java
yields
bytecode
file Jo.class
C:\demo>java Fred
Fred's age is 20
Jo's age is 21
©David Bish, Dept of Computing, Univ of Surrey
Slide 9
•Packages are a grouping mechanism for classes
but
... the classes in a package need not be
interrelated (e.g. though inheritance) can be
•Packages also define an access range …
... classes variables & methods can be made
accessible only within their own package
i.e. this is a wider access than class-wide scope
(but same if package contains just one class)
any variable, method or class not
This
designated ‘public’
public’ or ‘private’
private’ can be
is the
only within its own package
default accessed
(also within sub classes if ‘protected’
protected’)
Note: there is no keyword for this – it’
it’s just default
©David Bish, Dept of Computing, Univ of Surrey
Packages are Organised Hierarchically
Slide 11
•Two important packages at the top level of the
Java library are named java and javax.
… these have sub packages, e.g. java.lang is
the sub package lang in package java.
Snapshot of the Java Library System
java
lang
Math
String Wrappers
util
Scanner
©David Bish, Dept of Computing, Univ of Surrey
Slide 10
‘range of existence’
existence’ and ‘access’
access’ are not same thing
•public Æ accessible throughout the program
•private Æ accessible within same class only
•neither of these Æ accessible within same package
•protected Æ accessible within same package and
within sub classes
public class Fred
j exists only
{
within Fred
static public int j = 5;
public static void main (String [ ] args)
{
but
int m = 2;
since Fred and
System.out.print (m+" ");
j are public, j
System.out.print (j+" "); can be accessed
}
throughout the
.
program as
.
Fred.j
}
©David Bish, Dept of Computing, Univ of Surrey
•Each package can have sub-packages
… we see this in the Java library system.
javax
successful
run
only j has class
-wide scope
scope of m
moving
on
Output
compile
Fred.java
and
David.java
©David Bish, Dept of Computing, Univ of Surrey
Q What is a package?
A A collection of classes
revision Slide 8
text
Hierarchical organisation of packages Slide 12
maps directly to a machine’
machine’s directories
•Each package is represented on the machine as
a directory or folder with the same name
… each sub package is represented as a subdirectory or sub-folder
… each class is a .class file
in a package directory
higher
or sub-directory
directories
directories (i.e.
folders) must
java
have same names
as packages
lang
text
util
Math
String Wrappers Scanner
all .class files for Math
©David Bish, Dept of Computing, Univ of Surrey
©David Bish, Dept of Computing, University of Surrey – Spring Semester, 2008
Programming Languages 2 - week 7
Slide set B –
Packages
http://www.computing.surrey.ac.uk/personal/st/D.Bish
Slide 13
Slide 14
Putting classes in a named
Creating our Own Packages
source file with
• Every Java class resides in a package.
The Default Package
… if no named package is specified a for a class
it resides in the default package
… hitherto, all our code has been in the default
… using the default package is straightforward
providing you have the classpath setting correct
… be aware that the system searches for
default package classes slightly differently
than for named package classes
Q How can I specify that my classes A next
are in some named package?
slide
©David Bish, Dept of Computing, Univ of Surrey
package is easy …
classes Cat
Æ use ‘package’
package’ statement. and Dog both in a
package called
this takes
‘pets’.
package
name;
the form
package pets;
• A package statement must be
the first statement in source file
class Cat
… it specifies that all classes in
{
the file are in the package
.
.
… only one package statement
}
is allowed per source file
… classes in different packages
class Dog
must be in different source files
{
.
…but handling package
.
}
directories can be tricky
©David Bish, Dept of Computing, Univ of Surrey
Slide 15
First recall CLASSPATH (PL1, wk4)
In the notes for the very first week of PL1 we said:
By default, the system looks for bytecode for
your class in your current directory. “It is
possible to tell the system to look in another
location for a class using SET CLASSPATH …”
Setting CLASSPATH
Slide 16
(CLASSPATH was discussed PL1, Wk 4, document2)
Now learn that classpath can be an option at each run
C:\xxx>java –classpath D:\myclasses Fred
classpath setting
But it is nearly always
easier to set it as an environment variable.
now classpath is a list of places where a Java
learn compiler and Java Virtual Machine (JVM) can
that look for required .class files …
… typically it is a list of directories or folders.
If you do not set a classpath,
classpath, it is set automatically
to list of one item Æ your current directory.
In the APLabs,
APLabs, classpath is already set, but you may
need to add your own package directories to the list.
Important:
Important: ‘current directory’
directory’ is the automatic default
only if you do not set any classpath.
classpath. If you do set
classpath,
classpath, include the current directory (.;) explicitly .
©David Bish, Dept of Computing, Univ of Surrey
©David Bish, Dept of Computing, Univ of Surrey
Slide 17
Q How is classpath used?
A It is used by the Java system for locating both the
initial package (where main ( ) method resides) …
… and locating any other packages you use.
How the compiler & JVM search for classes
… they search ‘lib’
lib’ and ‘lib\
lib\ext’
ext’ directories (already
set up) – looking for packages like java.util
…
when looking for classes in the unnamed default
package, each directory in the classpath list is
searched for .class files(s).
files(s). (So be sure current
directory is included in your classpath list.)
… when looking for classes in named packages,
each directory in the classpath list is searched
for SUBDIRECTORIES with specified package
names.
©David Bish, Dept of Computing, Univ of Surrey
C:\xxx>SET CLASSPAT H= .; D:\myclasses
Here we list two CLASSPATH locations: the current
directory and the directory myclasses under disc D
Example Classes – Cat and Dog
Slide 18
These simple classes will be used in our examples.
class Dog
class Cat
constructor {
{
private int age;
private int age;
– sets a
cat’s or
Dog (int age)
Cat (int age)
dog’s age
{
{
this.age = age;
this.age = age;
}
}
getter
int getAge ( )
int getAge ( )
– gets a
{
{
cat’s
or
return age;
return age;
dog’s
}
}
age
}
}
(For simplicity we did not use inheritance
for these similar classes – but see slide 27.)
©David Bish, Dept of Computing, Univ of Surrey
©David Bish, Dept of Computing, University of Surrey – Spring Semester, 2008
Programming Languages 2 - week 7
Slide set B –
Packages
http://www.computing.surrey.ac.uk/personal/st/D.Bish
Slide 19
public class PetsProg
{
Example
Program
public static void main
using Cat and Dog classes
(String [ ] args)
{
no packages yet –
Cat myCat = new Cat (3);
i.e. all in default
Cat yourCat = new Cat (4);
package
Dog myDog = new Dog (5);
Dog yourDog = new Dog (6);
all three
System.out.println
classes in
("My cat's age is "
one file
+ myCat.getAge ( ));
System.out.println
create
two cats,
("Your cat's age is "
and two dogs
+ yourCat.getAge ( ));
System.out.println
ages 3, 4, 5, 6
("My dog's age is "
+ myDog.getAge ( ));
System.out.println
output all
("Your dog's age is "
their ages
+ yourDog.getAge ( ));
}
©David Bish, Dept of Computing, Univ of Surrey
}
One source file, all classes in package ‘pets’
pets’ Slide 21
compiles OK
package pets;
C:\demo>javac PetsProg.java
public class
PetsProg
C:\demo>java PetsProg
{
.
Exception in thread "main"
.
java.lang.NoClassDefFoundError:
}
PetsProg (wrong name:
class Cat
pets/PetsProg)C:\demo>
{
.
Run fails
.
because:
Demo
}
.class files are in class Dog
current directory {
but system wants .
PetsProg.java
.
to look for them
should be a
a subdirectory }
foldder ‘pets’! in
called ‘pets’.
©David Bish, Dept of Computing, Univ of Surrey
PetsProg still in Demo Slide 23
// no package
class
PetsProg is public
PetsProg.java
PetsProg
now
in
default
{
pets
package
.
.
C:\demo>javac PetsProg.java
}
PetsProg.java:7: cannot find symbol
Cat now in
symbol : class Cat
different
location: class PetsProg
package –
Cat myCat = new Cat (3);
need package
^
name
PetsProg.java:7: cannot find symbol
Demo
symbol : class Cat
location: class PetsProg
Cat myCat = new Cat (3);
^
………………..
got similar
failures for
other Cat and
Dog references
©David Bish, Dept of Computing, Univ of Surrey
Slide 20
C:\demo>javac PetsProg.java
C:\demo>dir
Volume in drive C has no label.
Volume Serial Number is 30AD-CC15
Directory of C:\demo
01/03/2007 10:41 <DIR>
.
01/03/2007 10:41 <DIR>
..
01/03/2007 10:43 291 Cat.class
01/03/2007 10:43 178 Dog.class
01/03/2007 10:43 923 PetsProg.class
01/03/2007 10:42 819 PetsProg.java
4 File(s)
2,211 bytes
2 Dir(s) 23,903,334,400 bytes free
C:\demo>java PetsProg
My cat's age is 3
Your cat's age is 4
My dog's age is 5
Your dog's age is 6
C:\demo>
Output
for previous
slide
compile
PetsProg.java
three
classes, so
three .class
files
successful
run
©David Bish, Dept of Computing, Univ of Surrey
Create subsub-directory pets.
pets.
put Cat & Dog in own files in subdirectory pets
C:\demo>cd pets
C:\demo\pets>javac Cat.java
C:\demo\pets>javac Dog.java
C:\demo\pets>dir
Volume in drive C has no label.
Volume Serial Number is 30AD-CC15
Directory of C:\demo\pets
03/03/2007 00:30 <DIR>
.
03/03/2007 00:30 <DIR>
..
03/03/2007 00:30 291 Cat.class
03/03/2007 00:26 146 Cat.java
03/03/2007 00:30 291 Dog.class
03/03/2007 00:26 144 Dog.java
4 File(s)
872 bytes
2 Dir(s) 23,870,918,656 bytes free
C:\demo\pets>
Slide 22
package pets;
class Cat
{
.
.
}
package pets;
class Dog
{
.
.
}
Cat & Dog
compile OK
©David Bish, Dept of Computing, Univ of Surrey
Slide 24
Now include package name
Cat and
Dog in
public class PetsProg
class pets
{
changes
were not
public static void main
in red
public – so
(String [ ] args)
cannot be
{
pets.Cat myCat = new pets.Cat (3);
accessed
pets.Cat yourCat = new pets.Cat (4);
from
pets.Dog myDog = new pets.Dog (5);
default
pets.Dog yourDog = new pets.Dog (6); package
.
C:\demo>javac PetsProg.java
PetsProg.java:7: pets.Cat is not public
in pets; cannot be accessed from
outside package
pets.Cat myCat = new pets.Cat (3);
^
…………………………
got similar
failures for
other Cat and
Dog
references
©David Bish, Dept of Computing, Univ of Surrey
©David Bish, Dept of Computing, University of Surrey – Spring Semester, 2008
Programming Languages 2 - week 7
Slide set B –
Packages
http://www.computing.surrey.ac.uk/personal/st/D.Bish
Slide 25
Make Cat and Dog public
Cat and Dog still in own files in package pets
package pets;
package pets;
public class Dog
public class Cat
{
{
private int age;
private int age;
public Dog (int age)
public Cat (int age)
{
{
this.age = age;
this.age = age;
}
}
public int getAge ( )
public int getAge ( )
{
{
return age;
return age;
}
}
}
}
changes in red
compiled OK – not shown
©David Bish, Dept of Computing, Univ of Surrey
C:\demo\pets>
add
classpath
which says
search up
one level
- now OK
©David Bish, Dept of Computing, Univ of Surrey
Winding Up
Directory of C:\demo
03/03/2007 10:59 <DIR>
.
03/03/2007 10:59 <DIR>
..
03/03/2007 10:58 <DIR>
pets
03/03/2007 11:00
933 PetsProg.class
03/03/2007 01:03
653 PetsProg.java
2 File(s)
1,586 bytes
3 Dir(s) 23,870,681,088 bytes free
for slide
24 with 25
compiles OK
pets package
directory with
Cat and Dog
C:\demo>java PetsProg
My cat's age is 3
Your cat's age is 4
My dog's age is 5
Your dog's age is 6
runs OK
Note about separate source files
Slide 28
• Packages bundle classes together for wide use
… in consequence classes usually public.
• Only one public class is allowed in a source file.
• Thus separate source files often used for classes.
import
changes to sl 24 in red
import
all classes
import pets.*;
• import allows
in pets
class PetsProg
classes in other public
packages to be { public static void main no ref
accessed without
(String [ ] args)
to pets
package name.
{
Cat myCat = new Cat (3);
specific classes
Cat yourCat = new Cat (4);
import pets.Cat; Dog myDog = new Dog (5);
import pets.Dog; Dog yourDog = new Dog (6);
.
©David Bish, Dept of Computing, Univ of Surrey
Slide 29
• In Java, all classes lie in packages.
• Because most classes in named packages are
public, they usually occur in separate source files.
• Classes not explicitly placed in a named package
will automatically lie in the default package.
• classpath is a list of places where the compiler
and JVM look for packages – this includes
searching for the default package.
• The Java system automatically searches the Java
libraries in the directories lib and lib\ext .
• If you don’t set classpath, it is set automatically
listing just your current directory ...
… if you do set classpath, your list must include
the current directory (no longer automatic).
©David Bish, Dept of Computing, Univ of Surrey
C:\demo>dir
Volume in drive C has no label.
Volume Serial Number is 30AD-CC15
Slide 26
Output
©David Bish, Dept of Computing, Univ of Surrey
Using Slide 27
package pets;
public class Kitten extends Cat Inheritance
{
public Kitten (int age)
{
Kitten
super (age);
class Kitten inherits
seeking
}
properties
and
}
‘pets’
methods of class directory
at
Cat on slide 25
its current
directory
C:\demo>cd pets
level
C:\demo\pets>javac Kitten.java
Kitten.java:2: cannot find symbol
symbol: class Cat
public class Kitten extends Cat
^
1 error
C:\demo\pets>javac -classpath .. Kitten.java
C:\demo>javac PetsProg.java
Winding Up - continued
Slide 30
• Packages are hierarchical and map on to the
directories (i.e. folders) of the machine.
• .class files must be stored in a directory bearing
their package name unless in the default package.
• Any named package in a program must feature in
the directory system as a directory lying directly
below some directory listed in classpath list.
• To use a class outside current package give the
package name and class name …
… else use import statement .
• If there is no public, private or
protected qualifier, then classes,
variables and methods can be
accessed only within the current
package.
The
End
©David Bish, Dept of Computing, Univ of Surrey
©David Bish, Dept of Computing, University of Surrey – Spring Semester, 2008
Download