44
COSC 2006 Data Structures I Instructor: S. Xu URL: http://people.auc.ca/xu

COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Embed Size (px)

Citation preview

Page 1: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

COSC 2006

Data Structures I

Instructor: S. XuURL: http://people.auc.ca/xu

Page 2: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Topics

Syllabus Java review

Page 3: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Java Review

Page 4: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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)

Page 5: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 6: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Import and Type References

Importing classes from packages import com.ibm.xml.parser.Parser; import com.ibm.xml.parser.*;

Page 7: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Classes Is this legal in the file name “Test.java”?

Import java.io.*;public class Test{public static void main (…){}

}class Lab1 { ……}

Page 8: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Classes

Is this legal in the file name “Test.java”?

Import java.io.*;public class Test{public static void main (…){}

}public class Lab1 { ……}

Page 9: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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.

Page 10: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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?)

Page 11: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 12: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Data Fields

Variables and Constants

[access-modifier] use-modifier* type name [= initializer];

public static final double DEFAULT_RADIUS = 1.0;

Page 13: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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 ...

Page 14: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 15: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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 ...

Page 16: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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();

Page 17: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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 … */

Page 18: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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;

Page 19: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 20: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

References

Assigning with newint x = 10;

Integer intObject = new Integer(x)

Primitives versus References Comparing with == Passing as arguments

Page 21: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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;

Page 22: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Operators for Primitives

Assignment = Arithmetic + - * / %

usual precedence, left associative Use () for clearer associativity

Combined: +=, -=, *=, /=, %=x += y;

Incrementing/Decrementing: ++, --++x;x++;

x += ++y; //?

Page 23: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Boolean Operators

Relational: <, <=, >=, > Equality: ==, != Logical: &&, ||

Page 24: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Selection: if

if (expression){statement+

}

if (expression){statement+

}else {

statement+}

if (expression){

statement+

}

else if (expression){

statement+

}

else {

statement+

}

Page 25: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Selection: switch

switch (integer-expression){case value1:

statement+// continues executing below!

case value2: case value3: … statement+break; // exits switch

… default:

statement+ // often an exception}

Page 26: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 27: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 28: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 29: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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);

Page 30: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Abstract Classes

This is an abstract class

public abstract class myClass {abstract void print ();int calculate (int x, int y) {

return x+y;}

}

Page 31: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Abstract Classes

Is this an abstract class

public abstract class myClass {

int calculate (int x, int y) {

return x+y;

}

}

Page 32: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 33: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 34: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Java interfaces

Interfaces just indicate what methods must be supplied

public interface Enumeration {

boolean hasMoreElements();

Object nextElement();

}

Page 35: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 36: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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)

Page 37: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Throwing Your Own

Class MyException extends Exception {public MyException(String s){

super(s);}}public void myMethod() throws MyException { // … code …throw new MyException("Indigestible

argument”); }

Page 38: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 39: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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

Page 40: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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];

Page 41: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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.

Page 42: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

42

Review ______The Java statement Object

element = new Object(); creates a:  new class new object new reference variable new container to hold objects

Page 43: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

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.

Page 44: COSC 2006 Data Structures I Instructor: S. Xu URL: //people.auc.ca/xu

Attentions Assignment 1 Start as early as possible