Arrays –Collections (Set, Database, History) Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables)

Slides:



Advertisements
Similar presentations
Chapter 21 Implementing lists: array implementation.
Advertisements

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.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Pointers Prasun Dewan Comp 114.
Written by: Dr. JJ Shepherd
C OMP 110/401 C OLLECTION K INDS Instructor: Prasun Dewan.
Inheritance Inheritance Reserved word protected Reserved word super
C OMP 110 A RRAYS Instructor: Jason Carter. 2 O UTLINE for loops Arrays.
C OMP 401 D YNAMIC D ISPATCH AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship –human IS-A.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Java Syntax Primitive data types Operators Control statements.
Inheritance and IS-A Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Scanning Scanning image for text. Scanning frequencies for radio stations. Finding words in a sentence Finding identifiers, operators, in a program char.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Comp 114 Foundations of Programming Instructor: Prasun Dewan (Pr  sün Divän)
Object-based Scanning Redo the scanning solution Monolithic, single class solution –does UI and scanning No reuse of code Another scanning problem to.
Java Unit 9: Arrays Declaring and Processing Arrays.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
JAVA PROGRAMMING PART II.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Object Oriented Programming: Java Edition By: Samuel Robinson.
Java Tutorial. Object-Oriented Programming Concepts Object –a representation of some item state  fields/members and should be encapsulated behavior 
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Chapter 2: Java Fundamentals
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
C OMP 401 A DVANCED G ENERICS Instructor: Prasun Dewan.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Object-based Scanning Redo the scanning solutions Monolithic, single class solutions –does UI and scanning No reuse of code.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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.
Written by: Dr. JJ Shepherd
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Classes Revisited Chapter 8.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
Chapter 9 Introduction to Arrays Fundamentals of Java.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
Object Oriented Programming Lecture 2: BallWorld.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
C OMP 401 D YNAMIC D ISPATCH AND V IRTUAL AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
Object-oriented Programming in Java
Chapter 11 Inheritance and Polymorphism
Comp 401 Dynamic Dispatch and Virtual and Abstract Methods
Recitation 6 Inheritance.
Introduction to Java Programming
Recitation 7 October 7, 2011.
Recitation 10 November 3, 2011.
Topics OOP Review Inheritance Review Abstract Classes
Presentation transcript:

Arrays –Collections (Set, Database, History) Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship –human IS-A Mammal –salmon IS-A Fish –“Joe Doe” IS-A Student –ALoan IS-A Loan

Strings = Char Sequences JohnF.Kenndye hello String{sequences of characters} 143l0

Other Sequences as Predefined Types {sequences of integers} 80 JFKFDR {sequence of Strings} JCBCRRGB {sequences of doubles} IntSequence DoubleSequence StringSequence

Sequences of Programmer-Defined Type loan1loan2 {sequence of loans} loan3 temperature1 {sequence of temperatures} temperature2temperature3 temperature1temperature2 TemperatureSequence LoanSequenceLoan[] Temperature[] Array Types Arrays Array Element

Other Sequences as Array Types {sequences of integers} 80 {sequence of strings} {sequences of doubles} int[] double[] String[] JFKFDRJCBCRRGB

Initializing Array Declarations int[] assignmentScores = {100, 98, 99, 80}; double[] gpas = {3.8, 3.1, 3.7, 3.1, 3.6, 3.9};String[] initials = {“JFK”, “FDR”, “JC”, “BC”, “GW”, “WW”}; JFKFDRJCBCGWWW assignmentScores Array Type Element Type Array Literal Array Variable

Initializing Array Declaration [] = {, …, } Loan [] loans = {new ALoan(100000), new AnotherLoan (100)};

Array Operations String[] initials = {“JFK”, “FDR”, “JC”, “BC”, “GW”, “WW”}; JFKFDRJCBCGWWW initials.length  6 initials[0] initials[initials.length - 1] initials[initials.length]  ArrayIndexOutOfBoundsException public named constant initials[0] = “HT” HT initials[initials.length] = “HT”  ArrayIndexOutOfBoundsException Array Instance Size Fixed

Array Types have Variable-Size int[] int[] assignmentScores = {100, 98, 99, 100, 99, 80}; assignmentScores assignmentScores = {60, 40, 50}; assignmentScores

Uninitializing Array Declaration int[] assignmentScores; assignmentScores null assignmentScores = {60, 40, 50}; assignmentScores

Array Elements Uninitialized int[] assignmentScores = new int[3]; assignmentScores 000

Object Array Elements Uninitialized String[] initials = new String[3]; initials null

Uninitialized Array Vs Element String[] initials = new String[3]; initials null String[] initials; initials null initials[0]  null initials[0] initials[0].charAt(0)  StringIndexOutOfBounds  ArrayIndexOutOfBoundsException

Example

getStrings() static String[] getStrings() { System.out.println("Number of Strings:"); int numElements = Keyboard.readInt(); System.out.println("Please enter " + numElements + " strings"); String[] strings = new String[numElements]; for (int elementNum = 0; elementNum < numElements; elementNum++) strings[elementNum] = Keyboard.readLine(); return strings; } variable

print() static void print(String[] strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.length; elementNum++) System.out.println(strings[elementNum]); System.out.println("******************"); } String array of arbitrary dimension (size)

main() public static void main(String[] args){ String[] names = getStrings(); while (true) { String command = Keyboard.readLine(); if (command.length > 0 && command.charAt(0) == 'q') break; if (command.length > 0 && command.charAt(0) == 'p') print(names); }

main()

Variable-Size Collection filled part unfilled part current size maximum size

3 James Dean Joe Doe Jane Smith sizearray Variable-Size Collection filled part unfilled part current size maximum size

Variable-Size Collection public class { … final static int A_MAX_SIZE = 50; String[] a = new String [MAX_SIZE]; int aSize = 0; … //process a for (int index = 0; index < aSize; index++) System.out.println(a[index]); … final int B_MAX_SIZE = 50; String[] b = new String [MAX_SIZE]; int bSize = 0; //process b … }

Special Type public class {... AVariableSizeCollection a = new AVariableSizeCollection();... for (int index = 0; index < a.size; index++) System.out.println(a.contents[index]); … AVariableSizeCollection b = new AVariableSizeCollection();... } public class AVariableSizeCollection { public static final int MAX_SIZE = 50; public String[] contents = new String [MAX_SIZE]; public int size = 0; } No encapsulation! a.contents[a.size] = Keyboard.readString(); Size not updated

Supporting Encapsulation public interface …. { public static final int MAX_SIZE = 50; } public void addElement (String element); public void print (); Implementation specific User specific

History public interface StringHistory { } public void addElement (String element); public int size(); public String elementAt (int index);

Implementing a History public class AStringHistory implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; }

Using a History public static void main(String[] args) { StringHistory names = new AStringHistory(); while (true) { String input = Keyboard.readLine(); if (input.length > 0) if (input.charAt(0) == 'q') break; else if (input.charAt(0) == 'p' ) print(names); else names.addElement(input); }

Printing a History static void print(StringHistory strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.size(); elementNum++) System.out.println(strings.elementAt(elementNum)); }

Database

public interface StringDatabase { //from history public int size(); public void addElement (String element); public String elementAt (int index); //additional methods } public void member (String element); public void deleteElement(String element); public void clear();

deleteElement (String element) 4 James Dean Joe Doe Jane Smith sizearray John Smith deleteElement(“Joe Doe”); public void deleteElement (String element) { contents[indexOf(element)] = contents[size - 1]; size--; } John Smith 3 Elements out of order!

deleteElement (String element) 4 James Dean Joe Doe Jane Smith sizearray John Smith deleteElement(“Joe Doe”); public void deleteElement (String element) { shiftUp(indexOf(element)); } 1 index

Multi-element window 4 James Dean Joe Doe Jane Smith sizearray John Smith deleteElement(“Joe Doe”); public void deleteElement (String element) { shiftUp(indexOf(element)); } Jane Smith 1 index contents[index] = contents[index + 1];

deleteElement (String element) 4 James Dean Joe Doe Jane Smith sizearray John Smith deleteElement(“Joe Doe”); public void deleteElement (String element) { shiftUp(indexOf(element)); } Jane Smith John Smith 3 void shiftUp (int startIndex) { for (int index = startIndex ; index + 1 < size; index++) contents[index] = contents[index + 1]; size--; } 2 index

indexOf (String element) 4 James Dean Joe Doe Jane Smith sizearray John Smith indexOf(“Joe Doe”); 0 index

indexOf (String element) 4 James Dean Joe Doe Jane Smith sizearray John Smith deleteElement(“Joe Doe”); 1 index public int indexOf (String element) { for ( index = 0; index < size && !element.equals(contents[index]; index++) ; return index; }

public boolean member(String element) 4 James Dean Joe Doe Jane Smith sizearray John Smith member(“Joe Doe”); public int indexOf (String element) { for ( index = 0; index < size && !element.equals(contents[index]; index++) ; return index; } public boolean member (String element) { } return indexOf (element) < size;

public void clear() 4 James Dean Joe Doe Jane Smith sizearray John Smith clear() public void clear() { while ( size > 0) deleteElement(size -1); } 3210

public void clear() 4 James Dean Joe Doe Jane Smith sizearray John Smith clear() public void clear() { size = 0; } 0

addElement(“Mary Doe”) 4 Mary Doe Joe Doe Jane Smith sizearray John Smith 1

Logical but not Physical Extensions clear( ) elementAt( ) size( ) member( ) deleteElement( ) addElement( ) String Database String History size( ) elementAt( ) addElement( ) IMPLEMENTS elementAt( ) member( ) deleteElement( ) indexOf( ) size( ) addElement( ) shiftUp( ) size contents MAX_SIZE AString Database clear( ) MAX_SIZE size contents size( ) addElement( ) elementAt( ) AString History isFull( )

Database public interface StringDatabase { //from history public int size(); public void addElement (String element); public String elementAt (int index); //additional methods } public void member (String element); public void deleteElement(String element); public void clear();

Physical and Logical Extensions String History size( ) elementAt( ) addElement( ) EXTENDS member( ) deleteElement( ) String Database clear( ) member( ) deleteElement( ) indexOf( ) shiftUp( ) AString Database clear( ) IMPLEMENTS EXTENDS Supertype Subtype MAX_SIZE size contents size( ) addElement( ) elementAt( ) AString History isFull( ) Superclass Subclass

Extending an Interface public interface StringDatabase extends StringHistory { } public void member (String element); public void deleteElement(String element); public void clear(); public interface StringHistory { } public void addElement (String element); public int size(); public String elementAt (int index); extends/ inherits from Inherited members

Extending a Class public class AStringDatabase extends AStringHistory implements StringDatabase { public void deleteElement (String element) { … } int indexOf (String element) { … } void shiftUp (int startIndex) { … } public boolean member(String element) { } public void clear() { } }

Physical and Computer Inheritance Human AStringDatabase Physical Object Animal Mammal Primate AStringHistory String Object Implicit extension Regular Accord Deluxe Accord Car Vehicle StringDatabase StringHistory

No Explicit Extension public class AStringHistory implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; }

Equivalent Class Definition public class AStringHistory extends Object implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; }

Some Methods of Class Object MAX_SIZE size contents size( ) addElement( ) elementAt( ) member( ) deleteElement( ) indexOf( ) shiftUp( ) AString Database AString History EXTENDS clear( ) isFull( ) Object EXTENDS toString( ) equals( ) clone( ) (new AStringHistory()).toString() (new AStringDatabase()).toString() (new ALoan()).toString() “hello”.toString() ‘h’.toString() 5.toString() Used by println()

IS-A Relationships Object StringHistoryAStringHistoryString AStringDatabaseStringDatabase implementsextends

IS-A & Polymorphism public static Loan add(Loan loan1, Loan loan2) { return new ALoan(loan1.getPrincipal() + loan2.getPrincipal())); } AnotherLoan Instance ALoan Instance Actual Parameters of different types IS-A

Printing a History static void print(StringHistory strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.size(); elementNum++) System.out.println(strings.elementAt(elementNum)); } AStringHistory Instance AStringDatabase Instance AStringHistory IS-A StringHistory AStringDatabase IS-A AStringHistory AStringDatabase IS-A StringHistory

Assignment Rules for Primitive Types If T1 narrower than T2 (Set of instances of T1  Set of instances of T2) Expression of type T1 can be assigned to Variable of type T2 Expression of type T2 can be assigned to Variable of type T1 with cast.

Assignment Rules for Object Types If T1 IS-A T2 Expression of type T1 can be assigned to Variable of type T2 Expression of type T2 can be assigned to Variable of type T1 with cast.

IS-A Definition Implements: T1 implements T2 => T1 IS-A T2 Extends: T1 extends T2 => T1 IS-A T2 Transitive: –T1 IS-A T2 –T2 IS-A T3 –=> T1 IS-A T3 Reflexive: –T1 == T2 => T1 IS-A T2

Type Checking Examples StringHistory stringHistory = new AStringDatabase(); StringDatabase stringDatabase = new AStringHistory();

Getting an Upgrade Regular Model Requested ARegularModel myCar = new ADeluxeModel (); ((ADeluxeModel) myCar). setCity(“Raleigh”); Deluxe Model Assigned myCar.steer(); Navigation System myCar. setCity(“Raleigh”);

Getting a Downgrade Deluxe Model Requested ADeluxeModel myCar = new ARegularModel (); Regular Model Assigned myCar.steer(); myCar. setCity(“Raleigh”);

Type Checking Examples StringHistory stringHistory = new AStringDatabase(); stringHistory.size() stringDatabase.clear() ((StringDatabase) stringHistory).clear() StringDatabase stringDatabase = new AStringHistory(); stringHistory.clear()

Type Checking Examples Object[] objects = { “Joe Doe”, new AStringDatabase(), new AStringHistory()}; String[] strings = { “Joe Doe”, new Object()};

Database

Set

Overriding Inherited Methods MAX_SIZE size contents size( ) addElement( ) elementAt( ) member( ) deleteElement( ) indexOf( ) shiftUp( ) AString Database AString History EXTENDS clear( ) isFull( ) Object EXTENDS toString( ) equals( ) clone( ) AString Set addElement( ) Overriden Method Overriding Method

Overriding addElement() public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; } public void addElement(String element) { if (member(element)) return; if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; }

super public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; } public void addElement(String element) { if (member(element)) return; super.addElement(); } inherited addElement()

Omitting Super public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; } public void addElement(String element) { if (member(element)) return; addElement(); } Recursive call

More Overriding MAX_SIZE size contents size( ) addElement( ) elementAt( ) member( ) deleteElement( ) indexOf( ) shiftUp( ) AString Database AString History EXTENDS clear( ) isFull( ) Object EXTENDS toString( ) equals( ) clone( ) AString Set addElement( ) Overriden Method Overriding Method toString( )

More Overriding public String toString() { String retVal = “”; for (int i = 0; i < size; i++) retVal += “:” + contents[i]; return retVal; } stringSet.toString()  stringSet.toString()  “James Dean:John Smith”

Motivation for Switch public static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q') break; else if (input.charAt(0) == 'p') print(names); else if (input.charAt(0) == 'd') names.deleteElement(input.substring(2, input.length())); else if (input.charAt(0) == 'm') System.out.println(names.member(input.substring(2, input.length()))); else if (input.charAt(0) == 'c') names.clear(); else names.addElement(input); }

Main with Switch public static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q') break; else switch (input.charAt(0)) { case 'p': print(names); break; case 'd': names.deleteElement(input.substring(2, input.length())); break; case 'm': System.out.println(names.member(input.substring(2, input.length()))); break; case 'c': names.clear(); break; default: names.addElement(input); } Breaks out of the loop Breaks out of the switch Switch expression Switch arm Switch case (value of switch expressiuon)

Multi-case arms public static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q') break; else switch (input.charAt(0)) { case 'p’, ‘P’: print(names); break; case 'd’, ‘D’: names.deleteElement(input.substring(2, input.length())); break; case 'm’, ‘M’: System.out.println(names.member(input.substring(2, input.length()))); break; case 'c’, ‘C’: names.clear(); break; default: names.addElement(input); }

Omitting break public static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q') break; else switch (input.charAt(0)) { case 'p’, ‘P’: print(names); case 'd’, ‘D’: names.deleteElement(input.substring(2, input.length())); case 'm’, ‘M’: System.out.println(names.member(input.substring(2, input.length()))); case 'c’, ‘C’: names.clear(); default: names.addElement(input); }

Illegal Switch switch (input ){ case “print”: print(names); case “clear”: names.clear(); default: names.addElement(input); } Type of switch expression must be ordinal type

Ordinal Type Values of type are ordered. Each value has a unique successor and predecessor intcharStringdouble