Data Structures Lecture 2

Similar documents
Object-Oriented Design. March 2005 Object Oriented Design 1

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Object-Oriented Programming

Introduction to Programming Using Java (98-388)

Data Structures Lecture 1

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 5 Object-Oriented Programming

Sorting. Sorting. Selection sort

CO Java SE 8: Fundamentals

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1

Chapter 4 Defining Classes I

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Introduction to Java for C/C++ Programmers. Kevin Squire Department of Computer Science Naval Postgraduate School

PROGRAMMING LANGUAGE 2

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

CMSC 341. Nilanjan Banerjee

IMACS: AP Computer Science A

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CSCI 355 Lab #2 Spring 2007

Inheritance and Polymorphism

Full file at Chapter 2 - Inheritance and Exception Handling

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

STRUCTURING OF PROGRAM

Tutorial 8 Date: 15/04/2014

Java Fundamentals (II)

Inheritance and Interfaces

The Java language has a wide variety of modifiers, including the following:

Computer Science II (20073) Week 1: Review and Inheritance

WA1278 Introduction to Java Using Eclipse

Programming Exercise 14: Inheritance and Polymorphism

15CS45 : OBJECT ORIENTED CONCEPTS

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Fundamentals of Object Oriented Programming

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Lecture 2: Java & Javadoc

CSCI 355 LAB #2 Spring 2004

COP 3330 Final Exam Review

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

C++ Important Questions with Answers

CS 116 Week 8 Page 1

CompuScholar, Inc. 9th - 12th grades

Programming II (CS300)

TeenCoder : Java Programming (ISBN )

C# Programming for Developers Course Labs Contents

public static boolean isoutside(int min, int max, int value)

Programming overview

Computer Science 210: Data Structures

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Final Examination Semester 3 / Year 2010

ITI Introduction to Computing II

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

More on Objects in JAVA TM

Exam Duration: 2hrs and 30min Software Design

Inheritance (Part 5) Odds and ends

Chapter 4.!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1

1Z0-808 oracle. Number: 1Z0-808 Passing Score: 800 Time Limit: 120 min.

Java Object Oriented Design. CSC207 Fall 2014

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

ITI Introduction to Computing II

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Introduction to Java

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

COMP 250: Java Object Oriented Programming

Object-Oriented Programming

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

CS 1331 Fall 2016 Exam 2

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Subclassing for ADTs Implementation

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Lab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018

AP CS Unit 6: Inheritance Notes

CS 11 java track: lecture 3

Introduction to Java Written by John Bell for CS 342, Spring 2018

Inheritance. Transitivity

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS313D: ADVANCED PROGRAMMING LANGUAGE

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

In this lab we will practice creating, throwing and handling exceptions.

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

CS-202 Introduction to Object Oriented Programming

Week 5-1: ADT Design

Making New instances of Classes

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Language Features. 1. The primitive types int, double, and boolean are part of the AP

What is Inheritance?

CMSC 132: Object-Oriented Programming II

Lecture 5: Methods CS2301

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Transcription:

Fall 2017 Fang Yu Software Security Lab. Dept. Management Information Systems, National Chengchi University Data Structures Lecture 2

Object-oriented Design Abstraction, Modularity, and Encapsulation

Abstraction Distills a system to its functionality [source:onanimation.com]

Abstract Data Type ADT (Abstract Data Type) Define ADT before implementation Specifies what each operation does, but not how it does (an interface in Java) An interface is a list of method declarations without their method body An ADT is realized by a concrete data structure (which is called a class in Java)

Modularity Splits a large program into a number of smaller, independent parts to reduce complexity Each part (a module) represents a separate functional unit [Source: php.jglobal.com]

Encapsulation Hide the implementation details of a module from its users Each module maintains a consistent interface but reveals no internal details for outsiders Gives the programmers the freedom in implementing the details [Source: entertainingcode.com]

Goals Software implementation should be Robustness Adaptability Reusability

Object-oriented Design An object Is the main actor in the object-oriented paradigm is an instance of a class A Class Defines an object Consists of fields and methods Gives others a consistent and concise view to interact with the object (without knowing details)

Inheritance A way to reuse code (based on a hierarchical structure) Player (A subclass) extends Human (A superclass) A player has his/her own name and record, and can watch, talk, jump, and shoot. Human Player extends Fields: name Methods: watch(), talk(), jump() Fields: record Methods: shoot()

Overriding Redefine a method in the subclass A player jumps in a different way A player has his/her own name and record, and can watch, talk, jump, and shoot. Human Player extends Fields: name Methods: watch(), talk(), jump() Fields: record Methods: jump(), shoot()

Polymorphism An object can be polymorphic. It may have different forms and behave the same method in different ways depending on which class it refers to For example, An instance of Human (like us) jumps in one way An instance of Player (like LeBron James) jumps in a different way How does Fang jump?

Overloading In the same class, one can define the same method with different signatures The signature of a method is a combination of its name, and the type and number of arguments Human Player extends Fields: name Methods: watch(), talk(), jump() Fields: record Methods: shoot(), shoot(int a)

this A keyword in Java The reference of the current instance of the class public class Example { public int dog =2; public void clobber() { int dog = 5; System.out.println( The local dog value = +dog); System.out.println( The field dog value = +this.dog); public static void main(string[] argv) { this.clobber(); javac Example.java java Example The local dog value = 5 The field dog value = 2

An inheritance example Progression 1, 2, 3, Arithmetic Progression f(n) = f(n-1)+d f(0) = 1, d =2, we have 1, 3, 5, 7, Geometric Progression f(n) = f(n-1)*r f(0) = 1, r = 2, we have 1, 2, 4, 8, 16, Fibonacci Progression f(n) = f(n-1)+f(n-2) f(0) =1, f(1) = 2, we have 1, 2, 3, 5, 8, 13, 21,

Progression Fields: first (the first value) cur (the current value) Methods: Progression(): Initialize the field values (A Constructor function) firstvalue(): Reset the progression to the first value and return that value nextvalue(): Step the progression to the next value and return that value printprogression(int n): Reset the progression and print the first n values

Progression //1, 2, 3, public class Progression { protected long first; protected long cur; Progression(){ //Constructor first = cur = 1; protected long firstvalue(){ //Reset cur cur = first; return cur; protected long nextvalue(){ //cur = cur+1; return cur; return ++cur; protected long printprogression(int n){

Progression //Print the first n values protected long printprogression(int n){ System.out.print(firstValue()); for(int i =2; i<=n; i++) System.out.print( + nextvalue()); System.out.println();

Arithmetic Progression first, first+d, first+2d, Progression extends ArithProgression Fields: first, cur Methods: firstvalue(), nextvalue(), printprogression() Fields: d Methods: nextvalue()

Arithmetic Progression //refines constructor, replaces nextvalue(), and //inherits Progression(), firstvalue(), printprogression(int) class ArithProgression extends Progression{ protected long d; ArithProgression(){ //d =1 by default this(1,1); //first=cur=1, d = 1; ArithProgression(int a, int increment) { //Set d to increment first =cur= a; d = increment; protected long nextvalue(){ cur += d; //cur = cur+d; return cur;

Geometric Progression first, first*r, first*r 2, Progression extends GeomProgression Fields: first, cur Methods: firstvalue(), nextvalue(), printprogression() Fields: r Methods: nextvalue()

Geometric Progression //refines constructor, replaces nextvalue(), and //inherits Progression(), firstvalue(), printprogression(int) class GeomProgression extends Progression { protected long r; GeomProgression(){ //first =1, r =1 by default this(1,1); //first = 1; r = 1; GeomProgression(int a, int base) { //Set r to base first = a; r = base; protected long nextvalue(){ cur *= r; //cur = cur*r; return cur;

Fibonacci Progression a0, a1, a2, a3, (a n+1 = a n-1 +a n ) Progression FiboProgression extends Fields: first, cur Methods: firstvalue(), nextvalue(), printprogression() Fields: prev Methods: nextvalue()

Fibonacci Progression //inherits Progression(), firstvalue(), printprogression(int) class FiboProgression extends Progression{ protected long prev; FiboProgression(){ //a0=1, a1=2 by default this(1,2); FiboProgression(long a0, long a1) { first = a0; //overwrite the initial value of first (so is cur) prev = a1-a0; //fictitious value preceding the first protected long nextvalue(){ //a n+1 = a n-1 +a n long temp = prev; //temp = a n-1 prev = cur; //prev = a n cur+=temp; //cur = a n+1 = a n-1 +a n return cur;

Inheritance Diagram Progression Fields: first, cur Methos: Progression(), firstvalue(), nextvalue(), printprogression(int) ArithProgression Fields: d Methods: ArithProgression(), ArithProgression(long), nextvalue() GeomProgression Fields: r Methods: GeomProgression(), GeomProgression(long), nextvalue() FiboProgression Fields: prev FiboProgression(), FiboProgression(long,long), nextvalue()

Test Progression class TestProgression{ public static void main(string[] args){ Progression prog; prog = new ArithProgression(1, 2); prog.printprogression(10); prog = new GeomProgression(1,3); prog.printprogression(10); prog = new FiboProgression(3,4); prog.printprogression(10); 1 3 5 7 9 11 13 15 17 19 1 3 9 27 81 243 729 2187 6561 19683 3 4 7 11 18 29 47 76 123 199

DoubleProgression //1, 2, 3, public class DoubleProgression { protected double first; protected double cur; Progression(){ //Constructor first = cur = 1; protected double firstvalue(){ //Reset cur cur = first; return cur; protected double nextvalue(){ //cur = cur+1; return cur; return ++cur; protected double printprogression(int n){

DoubleProgression //Print the first n values protected void printprogression(int n){ System.out.print(firstValue()); for(int i =2; i<=n; i++) System.out.print( + nextvalue()); System.out.println();

Geometric Double Progression //refines constructor, replaces nextvalue(), and //inherits Progression(), firstvalue(), printprogression(int) class GeomDoubleProgression extends DoubleProgression { protected double r; GeomProgression(){ //first =1, r =1 by default this(1,1); //first = 1; r = 1; GeomProgression(double a, double base) { //Set r to base first = a; r = base; protected double nextvalue(){ cur *= r; //cur = cur*r; if(cur<0) throw new Exception( negative value! ); return cur;

Test Progression class TestProgression{ public static void main(string[] args){ Progression prog; prog = new ArithProgression(1, 2); prog.printprogression(10); prog = new GeomProgression(1,3); try{ prog.printprogression(10); catch(exception abc){ System.out.println(abc.getValue()); prog = new GeomDoubleProgression(100,0.024); prog.printprogression(10); prog = new FiboProgression(3,4); prog.printprogression(10); 1 3 5 7 9 11 13 15 17 19 1 3 9 27 81 243 729 2187 6561 19683 3 4 7 11 18 29 47 76 123 199

Exception Handling Exceptions are unexpected events that occur during the execution of a program (by JRE or programmers) Throw an exception in Java throw new exception_type (param, ) Example: if (insertindex >= A.length){ throw new BoundaryViolationException( No element at index + insertindex);

Catching Exceptions When an exception is thrown, it must be caught Otherwise, the program will terminate Use try-catch block in Java to catch exceptions int index = Integer.MAX_VALUE; try{ String.toBuy = shoppinglist[index]; catch(arrayindexoutofboundsexception aioobx){ System.out.println( The index +index+ is outside the array. );

Interface Application Programming Interface (API) The methods that each object supports A list of method declarations with no data and no bodies Implementing Interfaces An interface enforces the requirements that a class has methods with certain specified signatures A class can implement many interfaces (must implement all methods of each interface)

An Interface and Its Implementation public interface Sellable { public String description(); public int listprice(); public int lowestprice(); public class Photo implements Sellable{ private String descript; private int price; private boolean color; public Photo(String desc, int p, boolean c){ descript = desc; price = p; color = c; public String description(){ return desc; public int listprice(){ return price; public int lowestprice(){ return price/2;

Multiple Inheritance An interface can have multiple inheritance (a class cannot) public interface Sellable { public String description(); public int listprice(); public int lowestprice(); public interface Transportable { public int weight(); public int ishazardous(); public interface InsurableItem extends Transportable, Sellable { public int insuredvalue();

Generics A generic type is not defined at compile time but becomes fully specified at run time Define a class with formal type parameters Instantiate an object of this class by using actual type parameters to indicate the concrete types

An Integer Pair Example public class IntPair{ string key; int value; public void set(string k, int v){ key = k; value = v; public string getkey(){ return key; public int getvalue(){ return value; public String tostring(){ return [ +getkey()+, +getvalue()+ ] ; public static void main( ){

An Double Pair Example public class DoublePair{ string key; double value; public void set(string k, double v){ key = k; value = v; public string getkey(){ return key; public double getvalue(){ return value; public String tostring(){ return [ +getkey()+, +getvalue()+ ] ; public static void main( ){

A Pair Example public static void main(string[] args){ IntPair pair1 = new IntPair(); pair1.set( age, 20); System.out.println(pair1.toString()); DoublePair pair2 = new DoublePair (); pair2.set(new String( grade ), new Double(82.53)); System.out.println(pair2.toString()); Javac Pair.java Java Pair [age, 20] [grade, 82.53]

A Generic Example public class Pair<K, V>{ K key; V value; public void set(k k, V v){ key = k; value = v; public K getkey(){ return key; public V getvalue(){ return value; public String tostring(){ return [ +getkey()+, +getvalue()+ ] ; public static void main( ){

A Generic Example public static void main(string[] args){ Pair<String, Integer> pair1 = new Pair<String, Integer>(); pair1.set(new String( age ), new Integer(20)); System.out.println(pair1.toString()); Pair<String, Double> pair2 = new Pair<String, Double>(); pair2.set(new String( grade ), new Double(82.53)); System.out.println(pair2.toString()); Javac Pair.java Java Pair [age, 20] [grade, 82.53]

Genetic Progression //1, 2, 3, public class Progression <k> { protected k first; protected k cur; Progression(){ //Constructor first = cur; protected k firstvalue(){ //Reset cur cur = first; return cur; protected k nextvalue(){ //cur = cur+1; return cur; return cur; protected k printprogression(int n){

Geometric Progression //refines constructor, replaces nextvalue(), and //inherits Progression(), firstvalue(), printprogression(int) class GeomProgression extends Progression<Long>{ protected long r; GeomProgression(){ //first =1, r =1 by default this(1,1); //first = 1; r = 1; GeomProgression(long a, long base) { //Set r to base first = a; r = base; protected long nextvalue(){ cur *= r; //cur = cur*r; return cur;

HW 2 (Due on 9/28) Generic Geometric Progression Output two different types of geometric progressions using inheritance and generics Try to throw/catch exceptions

The Growth Population Get initial population and years from user inputs (Use Scanner class) Every 30 years (a generation), the population becomes double Output the Population Progression (by generation) E.g., Input: 2 people and 120 years. Output: 2, 4, 8, 16, 32

The Growth of Capital Get initial capital and years from user inputs The annual interest rate is 2.4% Output the yearly Capital progression E.g., Input: 100 and 2 years. Output: 100, 102.4, 104.8576

Coming up We will discuss the team project, and text processing and pattern matching next week Read TB Chapter 12 We will have a makeup course on Sep 30 We will not have courses on Oct 5 and Oct. 12

Team Project: 30% 3-5 students as a team Send the team list (name and contact) to your TAs before the end of next week Develop your application using Eclipse with SVN TAs will help you set up SVN in the next week lab (Sep. 25) Start to work on it You will get extra points for updating your code constantly