Transcript Java Review

CSC311: Data Structures
Java Review
Fall 2006
CSC311: Data Structures
1
The Java Virtual Machine (JVM)
Virtual machine -- the logical machine (nonphysical machine) that performs machine
functions, typically implemented in software on
top of a "real" hardware platform and operating
system
JVM -- the software implementation of a "CPU"
designed to run compiled Java code
Includes stand-alone Java applications, as well
as "applets" that are downloaded and run in
Web browsers such as the NetScape Navigator
Thanks to the JVM, programs written in Java
don't have to be rewritten to run on different
computers
Need an interpreter to translate JVM code to
machine code
Fall 2006
CSC311: Data Structures
2
Class and Object
What is a class?
–
–
A class is corresponding to a concept, e.g.
People, Student, Faculty, Staff, Rectangle,
Circle, etc
In Java, a class is a set of objects with the
same behavior
What is an object?
–
–
–
–
Fall 2006
An object is corresponding an entity, e.g.
Jack, Peter
In Java, an object is an entity that you can
manipulate in your programs (by invoking
methods)
Each object belongs to a class
Object constructions
CSC311: Data Structures
3
Class Components
Components
– Fields – name, type and specifier
– Methods – signature (prototype)
– Constructors – object initialization
Declaration
– Variable declaration
– Object variables w/o initialization
– Method declaration // method calls
Fall 2006
CSC311: Data Structures
4
Data Types
Data types
– Primitive data types – int, long, short,
double, float, boolean, char
– Classes – String, Object
Type conversion
– Explicit type conversion – casting may
cause information lost
– Implicit type conversion – default no
information lost
Fall 2006
CSC311: Data Structures
5
Casting and Autoboxing/Unboxing
Casting:
(type) expr
Autoboxing
–
–
–
Implicit casting
Number – Integer, Double, Float, etc
Anytime a Number object is expected as a
parameter to a method, the corresponding
base type can be passed:
Number  base type
Unboxing
–
Fall 2006
Anytime a base type is expected in an
expression involving a Number reference,
that Number object is changed to the
corresponding base type
base type  Number
CSC311: Data Structures
6
Enum Types
Declaration
modifier enum name {vale_name0,
value_name1, …, value_namen-1
Example
Public enum Day{Mon, Tue, Wed, Thu,
Fri, Sat, Sun};
Constants -- final
Fall 2006
CSC311: Data Structures
7
Statements
Assignments – location
Decisions
–
–
–
If-then
If-then-else
Switch-case
–
–
–
while
do-while
for
–
–
–
break
continue
return
Iterations
Restricted gotos
Boolean expressions and short-circuit
evaluation
Fall 2006
CSC311: Data Structures
8
Simple Input and Output
Simple output methods:
–
Built-in static object: System.out
–
–
–
–
print(Object)
Print(String)
print(base_type)
Println(String)
–
–
–
Built-in special object: System.in
Related class: java.util.Scanner
Scanner sc = new Scanner(System.in);
hasNext()
next()
hasNextType()
nextType()
hasNextLine()
nextLine()
findInLine(String)
An instance of java.io.PrintStream class
Simple input methods
Fall 2006
CSC311: Data Structures
9
Designing classes
Choosing classes
–
–
A class represents a single concept
Concepts from mathematics: Point,
Rectangle, Ellipse
Concepts from real life: BankAccount, Person,
Student
Utility classes--no objects, only static methods
Math
Principles:
–
–
–
Fall 2006
Responsibilities
Independence
Behaviors
CSC311: Data Structures
10
Designing classes
Cohesion and Coupling
–
–
Cohesive: all methods are closely related to the
single concept that the class represents
Coupling: A class depends on another if it calls
one of its methods
High Coupling  many class dependencies
Minimize coupling to minimize the impact
of interface changes
Fall 2006
CSC311: Data Structures
11
Accessor and Mutator Classes
Accessor: does not change the state of
the implicit parameter (e.g. getBalance())
Mutator: changes the state of the implicit
parameter (e.g. deposit(double amount )
Rule of thumb: Mutator should return void
Immutable class: all methods are
accessors (e.g. String)
Fall 2006
CSC311: Data Structures
12
Preconditions/postconditions
Precondition
– The condition that must be met before
the method executes
– Publish preconditions so the caller
won't call methods with bad
parameters
Postcondition
– The condition that's true after a
method has completed
– If not, the method functioned
incorrectly
Fall 2006
CSC311: Data Structures
13
Scope
Scope of variable: region of program where the
variable can be referred by its name
– Local variable scope: from definition to end of block
– Class scope: all methods of the class
– Overlapping scope: local scope wins over class
scope
Static scope
– Static fields
Define a field that belongs to a class instead of
any object
Non-static fields are instance fields, while static
fields are class fields
Minimize the use of static fields
– Static methods
No implicit parameter
Too many static methods are a sign of too little
Object-oriented
Fall 2006
CSC311: Data Structures
14
Coding and Pseudo-code
Coding
– programming in Java
– IDE
Pseudo-code
– Mixes natural language with standard
programming language constructs
– Constructs:
Expressions
Method declarations
Decision structures
Loop structures
Array indexing
Method calls
Method returns
comments
Fall 2006
CSC311: Data Structures
15
Object-oriented Design
Goals
– Robustness
– Adaptability
– Reusability
Principles
– Abstraction
– Encapsulation
– Modularity
Design Patterns
– Describe a solution to a typical software design
problem
– Some typical design patterns: Position, Adaptor,
Iterator, Template method, Composition, Comparator,
Amortization, Divide-and-conquer, etc.
Fall 2006
CSC311: Data Structures
16
Inheritance
Specialization and generalization (extension)
– Specialization – subclass
– Generalization -- superclass
Method overriding
– Refinement
– Replacement
The keyword this
Fall 2006
CSC311: Data Structures
17
Inheritance Hierarchies
Hierarchies of classes, subclasses, and subsubclasses are common
Similar to concept hierarchies:
– Person has subclasses like Faculty, Student,
Staff;
– Faculty may have subclasses FullTimeFaculty
and PartTimeFaculty;
– FullTimeFaculty may have TenuredFaculty and
TenureTrackFaculty;
– Student may have subclasses FullTimeStudent
and PartTimeStudent;
– etc.
A superclass can have multiple subclasses, but a
subclass should have at most ONE superclass
Fall 2006
CSC311: Data Structures
18
Inheritance of Methods
Override method: Supply a different
implementation of a method that exists
in the superclass
Inherit method: Don't supply a new
implementation of a method that exists
in the superclass
Add method: Supply a new method that
doesn't exist in the superclass
Subclass can not access the private
methods of superclass
Calling a Superclass Method/constructor
Fall 2006
CSC311: Data Structures
19
Inheritance of Fields
Inherit field: All fields from the
superclass are automatically inherited
Add field: Supply a new field that doesn't
exist in the superclass
Can't override fields
Subclass can not access the private
fields of superclass
Fall 2006
CSC311: Data Structures
20
Polymorphism
Polymorphism (greek: many shapes):
The type of the object determines the
method to call
Called late binding. Resolved at runtime
Different from overloading. Overloading
is resolved by the compiler
Converting from subclasses to superclass
The instanceof method
– Test whether an object is of a specified class
– Example: x instanceof String to test if x is a
string
Fall 2006
CSC311: Data Structures
21
Access control
public – accessible anywhere
private – accessible inside the class
protected -- accessible by class,
subclasses and package
default – no specifier, accessible by
package
Recommended Access Levels
– Fields: Always private
Exception: public static final constants
– Methods: public or private
– Classes: public or package
– Don't use protected
– Beware of accidental package access
(forgetting public or private)
Fall 2006
CSC311: Data Structures
22
The Object Object
The Cosmic Superclass
All classes extend Object by default
Most useful methods:
– String toString(): to convert the object to a
string message
– boolean equals(Object otherObject): to test if
the object is equal to the given object
otherObject
– Object clone(): to create a new copy of the
object
Fall 2006
CSC311: Data Structures
23
Exceptions
Throwing exceptions
Catching exceptions
– Try-catch-finally block
try { … }
catch (exception_type1 e1) { … }
catch (exception_type2 e2) { … }
…
finally { … }
Fall 2006
CSC311: Data Structures
24
Interfaces
Special classes
All methods in an interface are abstract
– no implementation
All methods in an interface are
automatically public
An interface doesn't have instance fields
An interface doesn’t have constructors
Interface implementation
– Should be implemented by classes
Multiple inheritance in Interfaces
Fall 2006
CSC311: Data Structures
25
Abstract Class and Method
Abstract class
– Cannot have direct instances (objects)
– Must be extended by subclass(es)
– Can implement some methods (main
difference from interfaces)
Abstract method
– Must be overridden by subclass(es)
– Must be inside abstract classes
– Non-abstract class cannot have abstract
method
Fall 2006
CSC311: Data Structures
26
Strong Typing
Strong typing
– All variables must be typed
Java
– A strong-typing language
– An object can be viewed as being of
various types
– But declared as being of only one type
Fall 2006
CSC311: Data Structures
27
Generics
Casting
–
–
–
–
Widening conversion: to superclass
Narrowing conversion: to subclass
Casting exception
Casting with interfaces
Generics
– Generic type: a type that is not defined at
compilation time, but becomes fully specified
at run time
– Formal type parameters
– Actual type parameters
Fall 2006
CSC311: Data Structures
28
Generics: Example
public class Pair<K, V> {
K key;
V value;
public void set(K k, V v) {
key = k;
value = v;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
Public static void main(String[] args) {
Pair<String, integer> pair1 = new Pair<String, Integer>();
pair1.set(new String(“height”), new Integer(36));
Pair<String, Double> pair2 = new Pair<String, Double>();
pair2.set(new Student(“A5678”, “Sue”, 19), new Double(9.5));
}
}
Fall 2006
CSC311: Data Structures
29
Arrays
A set of data cells with fixed size, each cell
holding a data item and all data items being the
same type
Purpose: to construct a linear structure to hold a
given number of elements.
Once an array is created, its size is fixed – length
Indices starting from 0
Common algorithms on arrays
– Find max/min values
– Find average value
– Linear search
Copying array and clone array
High-dimensional arrays
Fall 2006
CSC311: Data Structures
30
Array List
ArrayList is a class – data type
Purpose: to construct a linear structure to hold a
flexible number of elements
Methods:
– size() – returns the number of elements in the
ArrayList: a.size()
– get(<index>) –
returns the <index>-th element that is the type of
Object
should convert the return value to your specific type
The <index> starts at 0
– set(<index>, <object>) – sets the <index>-th
element to <object>, overwrites the old
element
– add(<index>, <object>) – adds <object>
before the <index>-th element
– remove(<index<) – removes the <index>-th
element
Fall 2006
CSC311: Data Structures
31
Recursion
A recursive computation solves a problem
by using the solution of the same problem
with simpler input
For recursion to terminate, there must be
special cases for the simplest inputs
The simplest case can be directly solved
The recursive cases should call the method
itself
Fall 2006
CSC311: Data Structures
32