Java Review Interface, Casting, Generics, Iterator.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Lecture 11: Polymorphism and Dynamic Binding Polymorphism Static (compile-time) binding Dynamic (run-time) binding.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
1 Genericity Parameterizing by Type. 2 Generic Class One that is parameterized by type  Works when feature semantics is common to a set of types On object.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Multiple Choice Solutions True/False a c b e d   T F.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Question of the Day  Write valid mathematical equation using: one addition operator (‘+’) one equality operator (‘=’)  Should have equal values.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Java Generics.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Lists and the Collection Interface Review inheritance & collections.
Chapter 18 Java Collections Framework
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
LECTURE 9: INTERFACES & ABSTRACT CLASSES CSC 212 – Data Structures.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Classes Revisited Chapter 8.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Java Programming Language
Lecture 26: Advanced List Implementation
Dynamic Data Structures and Generics
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

Java Review Interface, Casting, Generics, Iterator

Interface A group of empty methods – design blueprint Public interface Stack { public Object pop(); public void push(); public int size(); } Can you define an object of type Stack? Stack aStack; Can you instantiate an object like this? aStack = new Stack();

Implementing Interface Public class ArrayStack implements Stack { … }

Use Interface as Type You can use interface names anywhere you can use any other data type name. Stack aStack; If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. aStack = new ArrayStack();

Java Multiple Inheritance through interface Can you do this? Public class myC extends myA, myB { } Can you do this? Public interface C extends A, B { public int newMethod(); }

Java Multiple Inheritance through interface Can you do this? Public class myCD implements C, D { } Can you do this now? myCD obj1 = new MyCD(); C obj2 = new MyCD(); D obj3 = new MyCD(); What are the real differences for the above obj1, obj2, obj3? They are references to three different objects of class type myCD.

Reference and primitive data Variable of primitive type int x, y; x = 5; y = x; //copy x to y x = 4; What is value of X, Y? Variable of reference myObj obj1, obj2; Obj1.x = 5; obj2 = obj1; //???copy obj1 to obj2??? Obj2.y = 4 What is value of obj1.x? How to copy an object? How to compare two objects to see if they have same information? Can you do obj1==obj2?

Casting – Type conversion Widening conversion – Cast a class type to its super class type – Cast a interface type to its super interface type – Cast a class type to the interface type it is implementing Example Object obj; obj = new MountainBike(); Stack aStack; aStack = new ArrayStack();

Casting – Type Conversion Narrowing conversion – Require explicit cast – Opposite of widening conversion Cast a superclass type object to subclass type Cast a superinterface type to subinterface type Cast a interface type to the class type who implemented the interface Example Object obj; MountainBike myBike; … myBike = (MountainBike)obj;

Casting exception Cast an object reference o of type T to type S – If o is indeed referencing an object of type S, fine. – Otherwise, exception “ClassCastException” will be thrown Use try-catch Use instanceOf to test – Object_reference instanceof reference_type if (obj instanceof MountainBike) { MountainBike myBike = (MountainBike)obj; }

What is the output of Demo? Public Class Fruit { public void getName() { System.out.println(“My name is fruit”); } Public Class Apple extends Fruit{ public void getName() { System.out.println(“My name is Apple”); } Public class Demo { Public static main(…) { Fruit fruit= new Apple(); fruit.getName(); }

Dynamic binding Static type the declared type of a variable Dynamic type The most child-like type of the variable at run-time Static binding happens at compiler time Dynamic Binding happens at run time overridden methods are bonded using dynamic binding

public class Test { public boolean equals(Test other) { System.out.println("Inside of Test.equals"); return false; } public static void main(String[] args) { Object t1 = new Test(); Object t2 = new Test(); Test t3 = new Test(); Object o1 = new Object(); int count = 0; System.out.println(count++);// prints 0 t1.equals(t2); System.out.println(count++);// prints 1 t1.equals(t3); System.out.println(count++);// prints 2 t3.equals(o1); System.out.println(count++);// prints 3 t3.equals(t3); System.out.println(count++);// prints 4 t3.equals(t2); }

Generics – formal type A generic type is a type that is not defined at compilation time – formal type parameters Public class Pair { K key; V value; public void set(K k, V v) { key = k; value = v; }

Generics - instantiation How to instantiate an object of the class that is defined with formal type? Pair pair1 = new Pair (); pair1.set(new String(“height”), new Integer(36)); Pair pair2= new Pair (); Pair2.set(new Student(“A5976”,”Sue”,19), new Double(9.5)); How to limit the formal type? Public class Directory

Generics - method How to define formal types which are used only in a method, not the scope of the class? – writing a method that takes an array of objects and a collection and puts all objects in the array into the collection static void fromArrayToCollection(T[] a, Collection c) { for (T o : a) { c.add(o); }

Why Generics Many data structures and algorithms do not relay on the type of data being manipulated For example: Stack, Queue Java Generic feature captures this idea Can we use Object instead of formalized type parameter? Yes. But generic Eliminate many casting Compile time type checking – Avoid run time type conversion error – Code is easy read

Generic interacts poorly with arrays 3 bad interactions that you are likely to encounter Basic generic array Array of parameterized type Array of inner classes inside parameterized types

Basic generic array Class Foo { void m() { E[] localArr; //This is fine. //localArr = new E[SOME_SIZE]; //Doesn’t work! localArr = (E[]) new Object[SOME_SIZE]; //work around #1 } Yes, working around #1 will generate a warning. Just accept it.

Array of a parameterized type Java allows an array to be defined with a parameterized type Pair [] a; But it does not allow a parameterized type to be used to create a new array a = new Pair [10]; // Doesn’t work! But you can initialize with a nonparametric array (raw type), and cast it a = (Pair []) new Pair[10]; // workaround #2

Array of inner classes inside parameterized types Class C { class D { // inner class … } //D[] array = new D[100]; // Doesn’t work! Annoying! D[] array = (D[]) new C.D[100]; // Workaround #3 } Class D does not have generic parameters, why not working? Because class D is actually C.D, and D[] array = new D[100] is actually C.D[] array = new C.D[100] It is indeed the very similar to the workaround #2

Don’t shadow type parameters in inner classes Class C { class D { // inner class … } Class C { E x; class D { // inner class E y = x; // compile error - not the same type! } Class C { E x; class D { // inner class E y = x; // this works fine. }

Traverse the items It is a common task to cycle through a collection of objects. array – index linked list – pre/next pointer tree – children pointers The easy way to do it is to employ an iterator, which is an object that implements the Iterator interface. Iterator is a Java interface with methods hasNext(), next(), remove() Iterator enables you to cycle through a collection, obtaining or removing elements. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection.

How to use iterator 1.Obtain an iterator by calling the collection's iterator( ) method 2.Have the loop iterate as long as hasNext( ) returns true. 3.Within the loop, obtain each element by calling next( ).

Iterator example – while loop import java.util.*; public final class LoopStyles { public static void main( String... aArguments ) { List flavours = new ArrayList (); flavours.add("chocolate"); flavours.add("strawberry"); flavours.add("vanilla"); useWhileLoop( flavours ); useForLoop( flavours ); } private static void useWhileLoop( Collection aFlavours ) { Iterator flavoursIter = aFlavours.iterator(); while ( flavoursIter.hasNext() ){ System.out.println( flavoursIter.next() ); }

Iterator example – for loop // Note that this for-loop does not use an integer index. private static void useForLoop( Collection aFlavours ) { for ( Iterator flavoursIter = aFlavours.iterator(); flavoursIter.hasNext(); ) { System.out.println( flavoursIter.next() ); } // Use for - each loop. More easy to make iteration over arrays or other collections private static void useForLoop( Collection aFlavours ) { for ( String flavour : aFlavours ) { System.out.println( flavour ); }