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

Post on 04-Jan-2016

33 views 0 download

Tags:

description

COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University yingcai@iastate.edu 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

COM S 228Introduction to Data Structures

Instructor: Ying Cai

Department of Computer ScienceIowa State Universityyingcai@iastate.eduOffice: Atanasoff 201

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

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

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

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

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

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}

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

Interface Implementation

An interface is basically a contract between module writers

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

Other Implementations

A same interface can have more than one implementation

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

Implementation of Multiple Interfaces

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

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.

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

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

Dynamic bindingLet p be a reference to an object

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

Suppose we also want to implement a Cat class

now getName() is duplicated

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.

Updated Class Hierarchy

More Example

Implementation through Interface

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

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

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

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];

// 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);

Copy and Clone()

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

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

}

Copy and Clone()

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

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

copy.setY(this.y);}

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();

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;}

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]; } }}

Static Variables Also called class variables

Shared by a whole class of objects

Static Method Does not implicit pass an object as its

parameter

Usage: Human.printHumans()

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);}

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