Download presentation
Presentation is loading. Please wait.
Published byHannah Hartell Modified over 10 years ago
1
COSC 2006 Data Structures I Instructor: S. Xu URL: http://people.auc.ca/xuhttp://people.auc.ca/xu
2
Topics Syllabus Java review
3
Java Review
4
What’s in what? Program [Packages (each in its own directory) ] Classes (each in own.java file) Data Fields Methods (if it is an application, one main)
5
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
6
Import and Type References Importing classes from packages import com.ibm.xml.parser.Parser; import com.ibm.xml.parser.*;
7
Classes Is this legal in the file name “Test.java”? Import java.io.*; public class Test{ public static void main (…){ } } class Lab1 { …… }
8
Classes Is this legal in the file name “Test.java”? Import java.io.*; public class Test{ public static void main (…){ } } public class Lab1 { …… }
9
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.
10
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 new new OrderedTree() … (why is this wrong?)
11
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
12
Data Fields Variables and Constants [ access-modifier] use-modifier* type name [ = initializer]; public static final double DEFAULT_RADIUS = 1.0;
13
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...
14
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
15
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...
16
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();
17
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 … */
18
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;
19
Primitive Types and Wrappers
20
References Assigning with new int x = 10; Integer intObject = new Integer(x) Primitives versus References Comparing with == Passing as arguments
21
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;
22
Operators for Primitives Assignment = Arithmetic + - * / % usual precedence, left associative Use () for clearer associativity Combined: +=, -=, *=, /=, %= x += y; Incrementing/Decrementing: ++, -- ++x; x++; x += ++y; //?
23
Boolean Operators Relational: =, > Equality: ==, != Logical: &&, ||
24
Selection: if if ( expression ){ statement+ } if ( expression ){ statement+ } else { statement+ } if ( expression ){ statement+ } else if ( expression ){ statement+ } else { statement+ }
25
Selection: switch switch ( integer-expression ){ case value1: statement+ // continues executing below! case value2: case value3: … statement+ break; // exits switch … default: statement+ // often an exception }
26
Iteration: while, do, for // 0 or more times while ( expression ){ statement+ } // at least once do { statement+ } while ( expression ); for ( initialize* ; [test] ; update* ){ statement* } // equivalently initialize ; while ( test ) { statement* ; update* ; } break and continue can be used in any iterator
27
Arrays Ordered collection of elements of uniform type with random access by index final int NUM_STUDENTS = 70; int [] grades = new int[NUM_STUDENTS]; Can initialize with values int [] grades = {92, 56, 87, 79, …}; Indices 0 to length-1 grades[0], grades[k], grades[k++], etc
28
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
29
More Arrays Array of objects SimpleSphere[] myMarbles = new SimpleSphere[BAG_CAPACITY]; Passing Arrays - Given: public int maxMarble(SimpleSphere[] bag) { … }; You can call it like this: int biggestMarble = maxMarble(myMarbles);
30
Abstract Classes This is an abstract class public abstract class myClass { abstract void print (); int calculate (int x, int y) { return x+y; }
31
Abstract Classes Is this an abstract class public abstract class myClass { int calculate (int x, int y) { return x+y; }
32
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
33
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
34
Java interfaces Interfaces just indicate what methods must be supplied public interface Enumeration { boolean hasMoreElements(); Object nextElement(); }
35
Exception Object-oriented generalization of “errors” try { statement* } catch ( exceptionClass1 identifier ) { statement*, e.g., identifier.printStackTrace() } // Zero or more of these finally { statement*, e.g., closing open files } // zero or one of these
36
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)
37
Throwing Your Own Class MyException extends Exception { public MyException(String s){ super(s); }} public void myMethod() throws MyException { // … code … throw new MyException("Indigestible argument”); }
38
More info Java 1.4/1.5 API http://java.sun.com/products/jdk/1.4/do cs/api/index.html http://people.auc.ca/xu/Link/javai nterview.PDF
39
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
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
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
42 Review ______The Java statement Object element = new Object(); creates a: new class new object new reference variable new container to hold objects
43
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.
44
Attentions Assignment 1 Start as early as possible
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.