DOC PREVIEW
UMD CMSC 132 - Object-Oriented Programming & Java Language Constructs

This preview shows page 1-2-19-20 out of 20 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1CMSC 132: Object-Oriented Programming IIObject-Oriented Programming & Java Language ConstructsDepartment of Computer ScienceUniversity of Maryland, College Park2Review of Java Language ConstructsBasic elementsPrimitive types, variables, constants, operatorsIf-else, switch, while, forClassesObject instancesCreating objects with newObject referencesThe null referenceInstance data, class (static) dataMethodsParameters, return values, polymorphism3Review of Java Language ConstructsInheritanceBase class, derived class, superMethod overriding (vs. overloading)Abstract methodsUp- and down-casting, getClass(), instanceofavoid overuse of these... leads to bad designsInterfaces1D ArraysCreating, indexingExceptionsTry-catch blocks4Iterator InterfaceIteratorCommon interface for all Collection classesUsed to process all elements in collectionPropertiesCan remove current element during iterationWorks for any collection5Iterator InterfaceInterface public interface Iterator {boolean hasNext( );Object next( );void remove( ); // optional, called once per next( )}EXAMPLE: IteratorExampleIterable Interface• Includes just one prototype:Iterator<T> iterator();• Most collections in the Java Collections Framework implement Iterable67Enhanced For LoopWorks for arrays and any class that implements the Iterable interface, including all CollectionsFor loop handles Iterator automaticallyEXAMPLE: IterableExampleEnhanced For LoopAlso works with arrays:String[ ] roster = {"John", "Mary", "“Alice", "Mark"};for (String student : roster) System.out.println(student);8Project #1Public JUnit testsConstructor does the workCreate any instance variables you wantNo need to do type casting (Use for-each loops)Try to make it FAST!910Enumerated TypesYou can create your own type with a finite number of values:public enum Color { Black, White } // new enumerationColor myC = Color.Black;New type of variable with set of fixed valuesSupports values(), valueOf(), name(), compareTo()…Can add fields and methods to enumsWhen to use enumsSets where you know all possible valuesEXAMPLE: EnumerationExample11Generics – Motivating ExampleBefore Generics…Collections using Object class:List x = new ArrayList();x.add(new Foo());Foo f = (Foo) x.get(0);Objects must be cast back to actual classProblem:x.add(new Bar());Foo f = (Foo) x.get(1); // compiles, but…// throws ClassCastException12Solution – Generic TypesGeneric typesList<Foo> x = new ArrayList<Foo>();x.add(new Bar()); // won’t compileImprovesReadability & robustnessUsed in Java Collections Framework13Autoboxing & UnboxingRecall: Wrapper classes available for primitives.Java will automatically convert back-and-forth:List<Integer> a = new ArrayList<Integer>();a.add(72); // auto-boxingint x = a.get(0); // auto-unboxingAlso see example in SortValues.java14Comparable Interface Comparablepublic int compareTo(Object o)A.compareTo(B) returnsNegative if A < B, 0 if A == B, positive if A > BPropertiesReferred to as the class's natural orderingUsed by Collections.sort( ) & Arrays.sort( )Will be used implicitly in certain CollectionsConsistency w/ equals( ) strongly recommendedx.equals(y) if and only if x.compareTo(y) == 0Also see Example: ComparableExample15Comparator Interface ComparatorUse to define orderings beyond the “natural order”Write a separate class for each orderingClasses implement the Comparator Interface:int compare(Object a, Object b)PropertiesSupports genericsExample: class myC implements Comparator<Foo>{ … }Used in many places in Collections Framework:Example: Collections.sort(myFooList, new myC( ) );EXAMPLE: ComparatorExample16Standard Input/OutputStandard I/O Provided in System class in java.lang System.in An instance of InputStreamSystem.out An instance of PrintStreamSystem.err An instance of PrintStream17Scanner Class ScannerRead primitive types & strings from input streamIncluding System.in (standard input)Provides methods to treat input as String, Integer…Supports String nextLine( ), int nextInt( )…Throws InputMismatchException if wrong format18Scanner Class ExamplesExample 1// old approach to scanning inputBufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String name = br.readLine( );// new approach using scannerScanner in = new Scanner(System.in);String name = in.nextLine( ); int x = in.nextInt( );192-D Arrays of PrimitivesEach row in two-dimensional array is an arrayRows can have different lengthsDefining a primitive array where rows have the same lengthint [ ][ ] data = new int[3][4];Defining a primitive data array where rows have different lengths (ragged array)int [ ][ ] ragged = new int[2][ ];ragged[0] = new int[3];ragged[1] = new int[1];202-D Arrays of ObjectsEach row in two-dimensional array is an arrayRows can have different lengthsDefining an array where rows have the same lengthString [ ][ ] data = new String[3][4];Important – Note we have created a 2-D array of references to String objects; no String objects yet existCan also create ragged arrays of objectsExample (See


View Full Document

UMD CMSC 132 - Object-Oriented Programming & Java Language Constructs

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Object-Oriented Programming & Java Language Constructs
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Object-Oriented Programming & Java Language Constructs and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Object-Oriented Programming & Java Language Constructs 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?