Download Lecture 5

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
OOP Lecture 5
Packages
JDK package from SUN
2
Introduction
• Packages are nothing more than the way we organize
files into different directories according to their
functionality, usability as well as category they should
belong to .
• A Java package is a Java programming language
mechanism for organizing classes into namespaces.
• For example, if we have a class name called "Vector", its
name would crash with the Vector class from JDK.
However, this never happens because JDK uses java.util
as a package name for the Vector class (java.util.Vector ).
3
Introduction
• Java source files belonging to the same category or
providing similar functionality can include a package
statement at the top of the file to designate the package
for the classes the source file defines.
• Java packages can be stored in compressed files called
JAR files.
4
Using Packages
• To use a package inside a Java source file, it is
convenient to import the classes from the package with an
import statement.
import java.awt.event.*;
• The above statement imports all classes from the
java.awt.event package.
5
Package access protection
• Classes within a package can access classes and
members declared with default access and class
members declared with the protected access modifier.
• Default access is enforced when neither the public,
protected nor private access modifier is specified in the
declaration.
6
Package Naming Conventions
• Packages are usually defined using a hierarchical naming
pattern, with levels in the hierarchy separated by periods
(.) .
• Although packages lower in the naming hierarchy are
often referred to a "subpackages" of the corresponding
packages higher in the hierarchy, there is no semantic
relationship between packages.
• Package names should be all lowercase characters
whenever possible. E.g.
• com.example.mypackage for a package
named mypackage created by a programmer
at example.com.
7
Package Design Guidelines
• Design Guideline Package Cohesion
• Only closely related classes should belong to the same package.
• Classes that change together should belong to the same package.
• Classes that are not reused together should not belong to the
same package.
8
Introduction to Java API
9
Contents
•
•
•
•
•
•
Java API Specifications
java.lang package
Object class
Class class
System class
String and StringBuffer classes
• Math class
• java.util package
10
Objectives
• Navigate the Java API Specifications
• Describe the java.lang package
• Explore fundamental classes in java.lang package:
•
•
•
•
•
•
Object
Class
System
String
StringBuffer
Math
• Describe the java.util package
11
Java API Specifications
http://java.sun.com/j2se/1.5.0/docs/api/
List of
Packages
List of
Classes
Package / Class
Description
12
java.lang package
• java.lang provides classes that are fundamental to the
design of the Java programming language.
• Object class, the root of the class hierarchy.
• Class class, represents classes at run time.
• Wrapper classes represent primitive types as objects.
• Math class provides mathematical functions.
• String and StringBuffer classes provide operations on
strings.
• System classes provide system operations.
• Throwable class represents errors and exceptions.
• java.lang is implicitly imported in every Java source
file.
13
Object class
Declaration: public class Object
•
Class Object is the root of the class hierarchy. Every class has
Object as a superclass. All objects inherit the methods of this class.
Method Summary
protected Object
boolean
protected void
Class<? extends Object>
int
clone()
equals(Object obj)
finalize()
getClass()
hashCode()
void
notify()
void
notifyAll()
String
toString()
void
wait()
void
wait(long timeout)
void
wait(long timeout, int nanos)
14
Class class
Declaration: public final class Class extends Object
implements Serializable, GenericDeclaration, Type,
AnnotatedElement
• Instances of the class Class represent classes and interfaces in a
running Java application.
• Every array also belongs to a class that is reflected as a Class
object that is shared by all arrays with the same element type and
number of dimensions.
• The primitive Java types (boolean, byte, char, short,
int, long, float, and double), and the keyword void are
also represented as Class objects.
• Class has no public constructor. Instead Class objects are
constructed automatically by the Java Virtual Machine as classes
are loaded in the class loader.
15
Class class
Method Summary (Partial List)
static Class
Class[]
Constructor[]
Field[]
Class[]
forName(String className)
getClasses()
getConstructors()
getFields()
getInterfaces()
Method[]
getMethods()
int
getModifiers()
String
Package
getName()
getPackage()
String
getSimpleName()
Class
getSuperclass()
boolean
isArray()
boolean
isInstance(Object obj)
boolean
isInterface()
boolean
isLocalClass()
boolean
isMemberClass()
boolean
isPrimitive()
16
System class
Declaration: public final class System extends Object
•
The System class contains several useful class fields and methods
which are related to the following operations:
• standard input, standard output, and error output streams.
• access to externally defined properties and environment variables.
• a means of loading files and libraries.
• and a utility method for quickly copying a portion of an array.
17
System class
Method Summary (Partial List)
Field Summary
static PrintStream
err
static InputStream
in
static PrintStream
out
static void
static String
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
clearProperty(String key)
static long
currentTimeMillis()
static void
exit(int status)
static void
gc()
static Map<String,String>
static String
static Properties
getenv()
getenv(String name)
getProperties() .
static SecurityManager
getSecurityManager()
static void
load(String filename)
static long
nanoTime()
static void
runFinalization()
static void
runFinalizersOnExit(boolean value)
static void
setErr(PrintStream err)
static void
setIn(InputStream in)
static void
setOut(PrintStream out)
static void
setProperties(Properties props)
static void
setSecurityManager(SecurityManager s)
18
String class
Declaration: public final class String extends Object
implements Serializable, Comparable<String>,
CharSequence
•
•
•
The String class represents character strings. All string literals in Java
programs are implemented as instances of this class.
Strings are immutable, their values cannot be changed after they are
created
The class String includes methods for examining individual
characters of the sequence, for comparing strings, for searching strings,
for extracting substrings, and for creating a copy of a string with all
characters translated to uppercase or to lowercase.
19
String class
Method Summary (Partial List)
char
int
String
charAt(int index)
compareTo(String anotherString)
concat(String str)
boolean
contains(CharSequence s)
boolean
endsWith(String suffix)
boolean
equals(Object anObject)
static String
format(String format, Object... args)
int
hashCode()
int
indexOf(int ch)
int
length()
boolean
String
String[]
boolean
matches(String regex)
replace(char oldChar, char newChar)
split(String regex)
startsWith(String prefix)
String
substring(int beginIndex)
String
toLowerCase()
String
toUpperCase()
String
trim()
20
StringBuffer class
Declaration: public final class StringBuffer
extends Object implements Serializable, CharSequence
• StringBuffer is a thread-safe, mutable sequence of characters. A
StringBuffer is like a String, but can be modified.
• StringBuffer class has been supplemented with an equivalent class
designed for use by a single thread, StringBuilder.
• The StringBuilder class should generally be used in preference to
StringBuffer as it supports all of the same operations but is faster
as it performs no synchronization.
21
StringBuffer class
Method Summary (Partial List)
StringBuffer
append(String str)
StringBuffer
append(StringBuffer sb)
int
char
capacity()
charAt(int index)
StringBuffer
delete(int start, int end)
StringBuffer
deleteCharAt(int index)
int
StringBuffer
indexOf(String str)
insert(int offset, String str)
int
lastIndexOf(String str)
int
length()
StringBuffer
replace(int start, int end, String str)
StringBuffer
reverse()
void
setCharAt(int index, char ch)
void
setLength(int newLength)
String
substring(int start)
String
substring(int start, int end)
String
toString()
void
trimToSize()
22
Math class
Declaration: public final class Math extends Object
• Math class contains methods for performing basic numeric
operations such as elementary exponential, logarithm, square root,
and trigonometric functions.
•
Math class cannot be extended (it is declared final) nor instantiated
(its constructor is private).
•
Its methods are declared static and can be invoked using its class
name.
23
Math class
Field Summary
static double
E
static double
PI
Method Summary (Partial List)
static double
abs(double a)
static double
ceil(double a)
static double
cos(double a)
static double
exp(double a)
static double
floor(double a)
static double
log(double a)
static double
log10(double a)
static double
log1p(double x)
static double
max(double a, double b)
static double
min(double a, double b)
static double
pow(double a, double b)
static double
random()
static long
round(double a)
static double
sin(double a)
static double
sqrt(double a)
static double
tan(double a)
static double
toDegrees(double angrad)
static double
toRadians(double angdeg)
24
Wrapper Classes
The wrapper classes serve two primary purposes:
•
To provide a mechanism to "wrap" primitive values in an object so
that the primitives can be included in activities reserved for objects,
such as being added to collections, or returned from a method with an
object return value.
•
To provide an assortment of utility functions for primitives. Most of
these functions are related to various conversions: converting
primitives to and from String objects, and converting primitives and
String objects to and from different bases (or radix), such as binary,
octal, and hexadecimal.
25
Wrapper Classes Constructors
Primitive
Wrapper Class
Constructor Arguments
boolean
Boolean
boolean or String or null
byte
Byte
byte of String
char
Character
char
double
Double
double or String
float
Float
float, double, or String
int
Integer
int or String
long
Long
long or String
short
Short
short or String
26
java.util package
Contains classes related to the following:
•
•
•
•
•
•
Collections framework
Legacy collection classes
Event model
Date and time facilities
Internationalization
Miscellaneous utility classes
• StringTokenizer, random-number generator, and bit array
27
Key Points
• The Java API is prewritten code organized into packages of similar topics
• java.lang provides classes that are fundamental to the design of the
Java programming language
• java.lang contains the following classes: Object, Class, Math,
String, StringBuffer, Throwable,Wrapper classes and System
classes
• java.lang package is implicitly imported in every Java source file
• Object is the superclass of all classes
• String objects are immutable
• java.util contains classes related to the following:
• Collections framework
• Legacy collection classes
• Event model
• Date and time facilities
• Internationalization
• Miscellaneous utility classes
28
Interactive programs
• We have written programs that print console output, but it
is also possible to read input from the console.
• The user types input into the console. We capture the input
and use it in our program.
• Such a program is called an interactive program.
• Interactive programs can be challenging.
• Computers and users think in very different ways.
• Users misbehave.
29
Input and System.in
• System.out
• An object with methods named println and print
• System.in
• not intended to be used directly
• We use a second object, from a class Scanner, to help us.
• Constructing a Scanner object to read console input:
Scanner name = new Scanner(System.in);
• Example:
Scanner console = new Scanner(System.in);
30
Java class libraries, import
• Java class libraries: Classes included with Java's JDK.
• organized into groups named packages
• To use a package, put an import declaration in your
program.
• Syntax:
// put this at the very top of your program
import packageName.*;
• Scanner is in a package named java.util
import java.util.*;
• To use Scanner, you must place the above line at the top
of your program (before the public class header).
31
Scanner methods
• nextInt()
• Reads a token of user input as an int
• nextDouble()
• Reads a token of user input as an double
• next ()
• Reads a token of user input as an String
• nextLine()
• Reads a line of user input as an String
32
CONT
• Each method waits until the user presses Enter.
• The value typed is returned.
System.out.print("How old are you? ");//prompt
int age = console.nextInt();
System.out.println("You'll be 40 in " +
(40 - age) + " years.");
• prompt: A message telling the user what input to type.
33
Example Scanner usage
import java.util.*;
// so that I can use Scanner
public class ReadSomeInput {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
int age = console.nextInt();
System.out.println(age + "... That's quite
old!");
}
}
•
Output (user input underlined):
How old are you? 14
14... That's quite old!
34
Another Scanner example
import java.util.*;
// so that I can use Scanner
public class ScannerSum {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please type three numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
int sum = num1 + num2 + num3;
System.out.println("The sum is " + sum);
}
}
•
Output (user input underlined):
Please type three numbers: 8 6 13
The sum is 27
• The Scanner can read multiple values from one line.
35
Input tokens
• token: A unit of user input, as read by the Scanner.
• Tokens are separated by whitespace (spaces, tabs,
newlines).
• How many tokens appear on the following line of input?
23 John Smith
42.0 "Hello world"
$2.50
" 19"
• When a token is not the type you ask for, it crashes.
System.out.print("What is your age? ");
int age = console.nextInt();
Output:
What is your age? Timmy
java.util.InputMismatchException
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...
36
Scanners as parameters
• If many methods read input, declare a Scanner in main
and pass it to the others as a parameter.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int sum = readSum3(console);
System.out.println("The sum is " + sum);
}
// Prompts for 3 numbers and returns their sum.
public static int readSum3(Scanner console) {
System.out.print("Type 3 numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
return num1 + num2 + num3;
}
37