COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

43
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University [email protected] Office: Atanasoff 201 Office Hours: MW 3:00pm-4:00pm

description

COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University [email protected] Office: Atanasoff 201 Office Hours: MW 3:00pm-4:00pm. Information Hiding Modularity. - PowerPoint PPT Presentation

Transcript of COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Page 1: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

COM S 228Introduction to Data Structures

Instructor: Ying Cai

Department of Computer ScienceIowa State [email protected]: Atanasoff 201

Office Hours: MW 3:00pm-4:00pm

Page 2: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Information Hiding Modularity

The basic idea is to build systems out of components that can be developed independently of each otherReducing coupling between components is the key developing complex systems, not just software

Page 3: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Abstraction

View components in terms of their essential features, ignoring details that aren’t relevant to our particular concerns

Each component provides a well-defined interface that specifies exactly how we can interact with it

Page 4: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Object-Oriented Programming

A system is a collection of interacting objects that communicate through well-defined interfacesAn object has three components

State: instance variables that hold some valuesIdentity: an object can be referred to and unique identifiedOperations: public interfaces (application programming interface)

A class is a type of an objectA class may have many objects

Page 5: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

OOP in Java: Class and Object

A program consists of one or more classesIn java, a class typically takes a single filePoint exampleBankAccount examples

Program

File

File

File

FileClas

sVariablesConstructors

Methods

Variables

Variables

Statements

Statements

Page 6: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

class BankAccount{ // account state stored in private variables private float balance; private String name; private String TransactionList; // etc

// public interface public void deposit(float amount) {

… } public double getCurrentBalance() { … } public double getTransactionList () { … }

public Report prepareMonthlyReport() { … } // etc}

Page 7: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Interface

An interface in Java defines a set of public methods without bodies For each method, it specifies a method name,

parameter types, and return types It is basically a contract between module writers,

specifying exactly how they will communicate

Page 8: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Interface Implementation

An interface is basically a contract between module writers

Bird is called a subtype of ISpeaking and ISpeaking a supertype of Bird

Page 9: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Other Implementations

A same interface can have more than one implementation

Page 10: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Some Notes

You can declare an object whose type is an interface:ISpeaking b; //OK

You cannot instantiate an interface variableISpeaking b = new Ispeaking(); //illegal

An interface variable must refer to an object of a class that implements the interfaceISpeaking b = new Bird(); //OK

All methods in a java interface are public

Page 11: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Implementation of Multiple Interfaces

Page 12: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Class ExtensionShare code and reduce redundancyAllow to add new attributes and methods

Retriever is a subtype or subclass of Dog;Dog is a supertype or a superclass of Retriever

Page 13: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 14: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Class Hierarchy By extension, classes may form a hierarchy Class hierarchy may be described as a class diagram, using Unified Modeling Language (UML)

We say Dog “implements” ISpeaking (dot line), Retriever extends Dog (solid line)We also say the subtype relation the “is-a” relation: A Retriever is a type of Dog, and a Dog is a type of ISpeaking.

Page 15: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

PolymorphismA variable of a given type T can hold a reference to an object of any of T’s subtypes

Ispeaking s = new Dog(“Thunder”, null)

The above statement does a few thingsIt invokes a constructor to instantiate an object of type Dog Some amount of memory is allocated to hold this objectThe constructor returns a reference to the object (or actually points to the memory address)It declares a variable s of type IspeakingThe value of s is set to be the reference (i.e., memory address)

Important NotesA Dog can be referenced by s because every Dog is an ISpeaking object, but not vice verseIn general, an object can hold a reference to any of its subtype

Page 16: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Static Type vs. Dynamic Type

Dog dog = new Dog();Bird bird = new Bird();ISpeaking s = null;

s = dog; // OK?s = bird; // OK?d = s; // OK? b = s; // OK?

Let p be a reference to an object Static type (compile time type) of P is the type of P when it is declaredDynamic type (runtime type) of P is the type of the object it references

Page 17: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Dynamic bindingLet p be a reference to an object

When p’s method is invoked, it is the object’s method that gets invoked

Page 18: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Suppose we also want to implement a Cat class

now getName() is duplicated

Page 19: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Abstract Class and Abstract Method

The idea is to eliminate duplicated code

Allow different implementation of speak() for different pets

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

Page 20: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Updated Class Hierarchy

Page 21: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

More Example

Page 22: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Implementation through Interface

Page 23: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Abstract Class and Abstract Method

A Java interface is just like an abstract class, except• A java class can inherit from only class,

but can implement multiple interfaces• A Java interface cannot implement any

method, it can only contain method prototypes and constants

Page 24: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Access Modifiers

private• Accessible only within the class, used for

implementation details

none or “package-private” (almost = protected)• Accessible from any class within the package

or by a subclass of its class in another package

protected• Accessible from subclasses, use when you

want any subclass to have access to a variable or method that is not public

public • Accessible from any class

Page 25: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

The root of java class hierarchy: java.lang.object

• toString(): return a string containing the class name and a hex number

• getClass(): return the object of type Class that represents the runtime class of the object

• equals(): return if two objects are the same, i.e., in the same memory

Page 26: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Memory AllocationVariable of primitive types• Value reference: It references to a memory that store

the actual value• 8 types (byte, short, int, long, float, double, boolean,

char)• Allocate at most 8 bytes

Variable of non-primitive types (i.e., objects)• Object reference: It references to a memory that

stores the address of the memory that stores the object

• Depending on the implementation of JVM, most likely 8 bytes (for 64-bit address space)

Array• treated as an object

int i = 100;

Object o = new Object();

int a[] = new int[100];

Object o[] = new Object[100];

Page 27: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

// what does this mean?Point r = q;

Point r = new Point(1, 2);Point q = new Point(1, 2);

r.equals(q)?

String s = “hurry”;String t = “HURRY”.toLowerCase()System.out.println(s == t);

System.out.println(s.equals(t);

Page 28: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Copy and Clone()

//1. Using constructorpubic Point(Point existing){

this.x = existing.getX();this.y = existing.getY();

}

Page 29: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Copy and Clone()

//2. Ad hoc cloningpubic Point makeClone(){

Point copy = new Point(); copy.setX(this.x);

copy.setY(this.y);}

Page 30: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Copy and Clone()

//2. Ad hoc cloningpubic Point makeClone(){

Point copy = new Point(); copy.setX(this.x);

copy.setY(this.y);}

Uaage: Point p = new Point(2, 4);q = p.makeClone();

Page 31: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Copy and Clone()

//3. Overriding Object.clone()pubic Object clone(){

Point copy = null;try

{ // super.clone() creats a copy of // all fileds copy = (Point) super.clone(); } catch (CloneNotSupportedException e) { } return copy;}

Page 32: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Shallow vs Deep Copyingpublic class IntVector { // Dimension (length) of this vector. private int dim; //The coordinates of this vector. private int[] coords; ::::

public IntVector(IntVector existing) { dim = existing.dim; coords = new int[dim]; for (int i = 0; i < dim; ++i) { coords[i] = existing.coords[i]; } }}

Page 33: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 34: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 35: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 36: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 37: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 38: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science
Page 39: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Static Variables Also called class variables

Shared by a whole class of objects

Page 40: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Static Method Does not implicit pass an object as its

parameter

Usage: Human.printHumans()

Page 41: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Variable Scope The scope of a variable is the part of the

program in which it is visible Local variable: defined within a method, ranged

from its declaration until the end of the block or for statement in which it is declared

public static void main(String[] args){ int sum = 0; for (int i=0; i<=10; i++) { int square = i * i; sum = sum + square; }

System.out.println(sum);}

Page 42: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

Exception Handling An exception is any special condition that alters

the normal flow of program execution divided by zero or open a file that does not exist,

etc.

Exception handler

Page 43: COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science