Upload
hannah-hartell
View
229
Download
3
Tags:
Embed Size (px)
Citation preview
COSC 2006
Data Structures I
Instructor: S. XuURL: http://people.auc.ca/xu
Topics
Syllabus Java review
Java Review
What’s in what?
Program
[Packages (each in its own directory)]
Classes (each in own .java file)
Data FieldsMethods (if it is an application, one
main)
Packages
package Package; - first line in file Each its own directory; can be nested
java.lang, java.io, java.util, etc. are each directories in the java directory
Import and Type References
Importing classes from packages import com.ibm.xml.parser.Parser; import com.ibm.xml.parser.*;
Classes Is this legal in the file name “Test.java”?
Import java.io.*;public class Test{public static void main (…){}
}class Lab1 { ……}
Classes
Is this legal in the file name “Test.java”?
Import java.io.*;public class Test{public static void main (…){}
}public class Lab1 { ……}
Classes A file can contain 0 to many top-level classes, but only one can be declared as public.
A top-level class can only be public or default.
Classes
Classes are data types: they specify data and methods for instances of the type[subclassing-modifier] [access-modifier] class ClassName [extends Class] [implements Interface] { body }abstract public class OrderedTree extends BinaryTree implements OrderedSequence { ... }
Make instances (objects) with newnew OrderedTree() … (why is this wrong?)
Parts of a Class Definition [subclassing-modifier]
abstract - must be extended final - cannot be extended
[access-modifier] public - available outside package protected private
class ClassName [extends Class] - inherits some data, methods [implements Interface] - conforms to method signatures
Data Fields
Variables and Constants
[access-modifier] use-modifier* type name [= initializer];
public static final double DEFAULT_RADIUS = 1.0;
Parts of a Data Declaration
[access-modifier] private - available only within the class None - available within class and package protected - available within class, other classes in
same package, and subclasses public - available everywhere the class is (exported)
use-modifier* static - one field shared across instances final - cannot be modified there are others ...
Methods
Operations[access-modifier] use-modifier* return-type methodName(formal-parameter-list){body}
public static int max(int x, int y){ ... } Parameters and actual values Call by value (except that only references to
objects are copied) return-type can be void or a type
Parts of a Method Declaration
[access-modifier] private - available only within the class None - available within class and package protected - available within class, other classes in same
package and subclasses public - available everywhere the class is
use-modifier* static - one shared across instances final - cannot be overridden by subclass abstract - must be overridden by subclass there are others ...
Referencing Members
Referencing Static Members: class.memberName SimpleSphere.DEFAULT_RADIUS
Or use object to access Referencing Public Members:
object.memberName SimpleSphere ball = new SimpleSphere()Ball.getVolume();
Comments
Javadoc Documentation/** * Prints out "Hello World" and the command line arguments. * @param arg A string array containing the arguments. * @return No return value. * @exception Exception if the file is not found or other error. */
Inline comments // this is inline
Disabling code/* … code … */
Identifiers
Identifiers: A-Z, a-z, 0-9, _, $ _ or letter first
Keywords: reserved identifiers Literal Constants:
12, 87.31, 8.7e-3, 'a', \n, '\'' Variables
int x; Named Constants
final int MAX_SIZE = 512;
Primitive Types and Wrappers
Category Data Type Wrapper Class Boolean boolean Boolean Character char Character Integer byte Byte short Short int Integer long Long Floating Point float Float double Double
References
Assigning with newint x = 10;
Integer intObject = new Integer(x)
Primitives versus References Comparing with == Passing as arguments
References & Objects
How many objects and how many references have been created?Worker wk1,wk2;
Adult ad1, ad2;
Wk1 = new Worker();
Wk2=wk1;
Ad1= new Adult ();
Ad2= wk1;
Operators for Primitives
Assignment = Arithmetic + - * / %
usual precedence, left associative Use () for clearer associativity
Combined: +=, -=, *=, /=, %=x += y;
Incrementing/Decrementing: ++, --++x;x++;
x += ++y; //?
Boolean Operators
Relational: <, <=, >=, > Equality: ==, != Logical: &&, ||
Selection: if
if (expression){statement+
}
if (expression){statement+
}else {
statement+}
if (expression){
statement+
}
else if (expression){
statement+
}
else {
statement+
}
Selection: switch
switch (integer-expression){case value1:
statement+// continues executing below!
case value2: case value3: … statement+break; // exits switch
… default:
statement+ // often an exception}
Iteration: while, do, for
// 0 or more times
while (expression){
statement+
}
// at least once
do {
statement+
} while (expression);
for (initialize* ; [test] ; update*){
statement*}
// equivalentlyinitialize;while (test) {
statement*;update*;
}
break and continue can be used in any iterator
Arrays
Ordered collection of elements of uniform type with random access by indexfinal int NUM_STUDENTS = 70;
int [] grades = new int[NUM_STUDENTS];
Can initialize with valuesint [] grades = {92, 56, 87, 79, …};
Indices 0 to length-1grades[0], grades[k], grades[k++], etc
More Arrays
Any wrong with this?int myArray[3]={1, 2, 3};
int myArray[]=new int [] {1,2,3} ; An array object (as distinct from reference)
is always initialized with zeroes for primitive type With nulls for object
More Arrays
Array of objectsSimpleSphere[] myMarbles = new SimpleSphere[BAG_CAPACITY];
Passing Arrays - Given: public int maxMarble(SimpleSphere[] bag) { … };
You can call it like this: int biggestMarble = maxMarble(myMarbles);
Abstract Classes
This is an abstract class
public abstract class myClass {abstract void print ();int calculate (int x, int y) {
return x+y;}
}
Abstract Classes
Is this an abstract class
public abstract class myClass {
int calculate (int x, int y) {
return x+y;
}
}
Abstract Classes
What’s an abstract class? If have abstract method, then class must be
declared abstract If you define the class as abstract, this is
abstract class even there is no abstract method
Abstract forces the class to be subclassed Can’t make instance of abstract class
Java interfaces
What is the difference between abstract class and interface?
Interface provides a way to have multiple inheritance
You can only inherit one abstract/normal class; but you can implements many interfaces
Abstract class can have partial behavior, but interface cannot
Java interfaces
Interfaces just indicate what methods must be supplied
public interface Enumeration {
boolean hasMoreElements();
Object nextElement();
}
Exception
Object-oriented generalization of “errors”try {
statement*}catch (exceptionClass1 identifier) {
statement*, e.g., identifier.printStackTrace()} // Zero or more of thesefinally {
statement*, e.g., closing open files} // zero or one of these
Exceptional!
try can be followed by zero or more catch blocks and zero or one finally block (at least one of catch or finally)
Finally block always be executed except for other reasons (such as machine crash)
Throwing Your Own
Class MyException extends Exception {public MyException(String s){
super(s);}}public void myMethod() throws MyException { // … code …throw new MyException("Indigestible
argument”); }
More info Java 1.4/1.5 API
http://java.sun.com/products/jdk/1.4/docs/api/index.html
http://people.auc.ca/xu/Link/javainterview.PDF
39
Review _________Which order is correct for the
access modifiers? A. public, default, protected, private B. private, default, protected, public C. default, private, protected, public D. protected, private, default, public
40
Review __________Which statement is wrong?
int myarray [3]={1,2,3}; int myarray []=new int []{1,2,3}; int [] myarray ={1,2,3}; int myarray []=new int [3];
41
Review _____ What is the common pattern of class
definitions A. Methods and instance variables are both private. B. Methods are private, and instance variables are
public. C. Methods are public, and instance variables are
private. D. Methods and instance variables are both public.
42
Review ______The Java statement Object
element = new Object(); creates a: new class new object new reference variable new container to hold objects
43
Review _______Can two different classes contain
methods with the same name? A. No.
B. Yes, but only if the two classes have the same name.
C. Yes, but only if the main program does not create objects of both kinds.
D. Yes, this is always allowed.
Attentions Assignment 1 Start as early as possible