34
Lecture 6: Data Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology Group www.win.tue.nl/ ˜ wstomv/edu/sc-hse c 2014, T. Verhoeff @ TUE.NL 1/34 Software Construction: Lecture 6

Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Lecture 6: Data Abstraction

Software Construction

in Java for HSE Moscow

Tom Verhoeff

Eindhoven University of Technology

Department of Mathematics & Computer Science

Software Engineering & Technology Group

www.win.tue.nl/˜wstomv/edu/sc-hse

c© 2014, T. Verhoeff @ TUE.NL 1/34 Software Construction: Lecture 6

Page 2: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Overview

• Homework Series 5

• Java class mechanism (basics)

• Data Types

• Data Abstraction: Ch. 5 in Eck

c© 2014, T. Verhoeff @ TUE.NL 2/34 Software Construction: Lecture 6

Page 3: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Homework Series 5

• Lots of good work has been submitted

• Still, also some not so good

• peach3 feedback is now open

• You can improve them until Tue 16 Oct 2013

• Aim for maximal scores

c© 2014, T. Verhoeff @ TUE.NL 3/34 Software Construction: Lecture 6

Page 4: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Recommendations for powerize()

• Do apply functional decomposition

• Do include some comment lines that explain your approach

• Do pay attention to performance (run time, memory)

• Do not use floating-point arithmetic on integers

• Hint

– Linear Search over exponents; start at largest exponent (30)

– Binary Search for base b, given a candidate exponent e:Find b with (b-1)ˆe < n <= bˆe (integer e-th root)N.B. 1ˆe < n <= nˆe; use given MathStuff.power (overflow!)

– Prime factorization works, but is slower and more work

c© 2014, T. Verhoeff @ TUE.NL 4/34 Software Construction: Lecture 6

Page 5: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Java class mechanism

The class concept plays a central role in the Java programming

language.

It is very general and “powerful”, and can easily be abused.

So far, we have used a class to collect static variables and methods.

In this lecture, we will learn to use it to define some data types :

• Enumeration type

• Record type

• Abstract Data Type (ADT)

c© 2014, T. Verhoeff @ TUE.NL 5/34 Software Construction: Lecture 6

Page 6: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Modularization: Top-down and Bottom-up Views

Top-down view :

• Given one (big) problem, split it into several (smaller) subproblems

• Continue until reaching trivially solvable problems

Bottom-up view

• Given many small solutions, combine them into bigger solutions

• Continue until reaching a solution of the main problem

Solutions could be: expressions, statements, data definitions, . . .methods, classes, interfaces, packages, programs, . . .

In practice: yo-yo design (top-down and bottom-up mixed)

c© 2014, T. Verhoeff @ TUE.NL 6/34 Software Construction: Lecture 6

Page 7: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Modularization for Actions

Procedural abstraction enables one to abstract from details within

• an expression

• a (possibly compound) statement

In Java, this is done by means of methods that

• modify a parameter object, and/or

• return a primitive value or (a reference to) an object, or

• return void

A method call acts as an expression or statement.

c© 2014, T. Verhoeff @ TUE.NL 7/34 Software Construction: Lecture 6

Page 8: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

(Limits to) Procedural Abstraction in Java

If expressions like p*p*p*p and (x+1)*(x+1)*(x+1)*(x+1)/2 occur invarious places, then this invites the procedural abstraction:

1 /** @return aˆ4 */2 int pow4(int a) {3 int h = a * a;4 return h * h;5 }6

7 .... pow4(p) ... pow4(x+1)/2 ....

(N.B. This implementation is also more efficient, in multiplications.How to generalize that for raising to the power n ≥ 0 efficiently?)

However, in Java it is impossible to define a procedural abstractioninc(v) for v = v + 1, where v is a parameter of type ”int variable”.

c© 2014, T. Verhoeff @ TUE.NL 8/34 Software Construction: Lecture 6

Page 9: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Modularization for Data: Data Abstraction (Bottom-up View)

Combine frequently occurring combinations of variables of primitivetypes into a single abstraction, instead of handling them separately.

• The numerator and denominator of a fraction

• The coefficients of a polynomial

• A pair (or triple) of coordinates of a point in the plane (in space)

• The first name, last name, and email address of a person

• Auxiliary path information in union-find (cf. Loop Puzzle Checker)

A data abstraction needs to be given a single name: variable vs type

In Java, this can be accomplished by String, array, and class , . . .However, only a class introduces a name for a new type.

c© 2014, T. Verhoeff @ TUE.NL 9/34 Software Construction: Lecture 6

Page 10: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Class as Bundle of Variables: Example

1 /** Data Type for fractions (simplistic). */2 public class Fraction {3

4 /** The numerator */5 long numerator;6

7 /** The denominator: > 0 */8 long denominator;9

10 // Operations on objects of this type.11 ...12 }13

14 ... Fraction q = new Fraction(2, 3);15 ... Fraction r = q.add(q);

c© 2014, T. Verhoeff @ TUE.NL 10/34 Software Construction: Lecture 6

Page 11: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Advantages and Disadvantages of a Record Type

Advantages (encapsulation):

• Less code clutter when declaring variables: one record variabledeclaration introduces multiple variables

• Can pass multiple variables in a record as one parameter

• Can return multiple variables in a record as result from function

Disadvantages (lack of information hiding):

• When changing the name of a field in a record, all using clientcode must be updated

• When changing the purpose, or mix of variables in a record, allusing client code must be updated

c© 2014, T. Verhoeff @ TUE.NL 11/34 Software Construction: Lecture 6

Page 12: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Modularization for Data: Data Abstraction (Top-down View)

What data items to distinguish and put in separate ‘modules’ ?

Which concepts play a role?

Nouns in requirements serve as a hint for data abstractions.

Verbs hint at operations on the data.

Hierarchic decomposition . . .

Possibly recursive, i.e. in terms of itself . . .

E.g.: a Rectangle involves Points, each Point has Coordinates.

A BinaryTree is either empty, or has a root and two BinaryTree-s.

c© 2014, T. Verhoeff @ TUE.NL 12/34 Software Construction: Lecture 6

Page 13: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Type

A (data) type is a set of values and accompanying operations.

Primitive data types in Java: int, double, char, boolean, ...Values in subset of Z, subset of R, { . . . ,’a’, . . . }, {false, true }

Type usage:

1 T v; // declares variable v of type T2 // during execution, v has one value of type T3

4 ... v ... // usage of v in operations; depends on T5 ... ++ v ... // for an int6 ... v = Math.sqrt(v); // for a double7 ... ! v && w ... // for a boolean8 ... v[2] ... // for an array

Cf. Type Theory and Type System

c© 2014, T. Verhoeff @ TUE.NL 13/34 Software Construction: Lecture 6

Page 14: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Data Type Constructors in Java: Enumerations

public class PrimaryColor {final static int RED = 0;final static int GREEN = 1;final static int BLUE = 2;

}

int v = PrimaryColor.RED; // a variable v having a primary color as value

or (why useful?):final static int RED = 1;final static int GREEN = 2;final static int BLUE = 4;

Better (since Java 5.0):

public enum PrimaryColor { RED, GREEN, BLUE }PrimaryColor v = PrimaryColor.RED; // ...

c© 2014, T. Verhoeff @ TUE.NL 14/34 Software Construction: Lecture 6

Page 15: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Java Enumeration Types

public enum T { NAME1 , NAME2 , ... , NAMEn }

Set of values: the set of listed names

Operations (involving v, w of type T):

• constants (by their name): NAME1, . . .

• iteration: for (T v : T.values()) { ... v ... }

• selection: switch (v) { case NAME1: ...; break; ... }

• conversion to/from string: v.name(), v.toString(), T.valueOf(s)

• ranking: v.ordinal() (ranks start at 0), v.compareTo(w)

c© 2014, T. Verhoeff @ TUE.NL 15/34 Software Construction: Lecture 6

Page 16: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Data Type Constructors in Java: ‘Records’

/** Record type for

* the coordinates of a field on a chess board.

*/

public class ChessBoardField {

public char line; // ’a’ .. ’h’

public int row; // 1 .. 8

}

ChessBoardField f; // value: the coordinates of a chess field

... f.line ... f.row ... // using variable f

(Also see DivisionResult in Candy example)

c© 2014, T. Verhoeff @ TUE.NL 16/34 Software Construction: Lecture 6

Page 17: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Java ‘Record’ Types via Classes

public class T {

public Type1 fieldName1 ;

... ;

public TypeN fieldNameN ;

}

Set of values: Labeled product of the value sets of the types,

mapping fieldName1 to Type1, etc.

Operations:

• field access (projection on field name): v.fieldName1, . . .

c© 2014, T. Verhoeff @ TUE.NL 17/34 Software Construction: Lecture 6

Page 18: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type (ADT): Definition of Concept

An Abstract Data Type is a type whose specification and usage

abstracts from (i.e. does not depend on) implementation details.

The implementation deals with the choice of data representation and

algorithms for operations on that representation.

The implementation of an ADT can be changed, without affecting

the usage occurrences, provided it adheres to the ADT’s specification.

This is called implementation hiding , also known as encapsulation .

An ADT can serve as a module of a program.

c© 2014, T. Verhoeff @ TUE.NL 18/34 Software Construction: Lecture 6

Page 19: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type: Specification Plays Central Role

contract↗ ‖ ↖

usage ‖ implementation‖

• Relate usage to contract and

relate implementation to contract.

• Never relate usage and implementation directly.

That way, ‘divide’ would fail,

leading to complexity and errors, en hence not to ‘conquer’.

c© 2014, T. Verhoeff @ TUE.NL 19/34 Software Construction: Lecture 6

Page 20: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type: Specification of Syntax

• Type name

• Operations (methods) with names and typed parameters:

– Constructor, destructor (memory management)

N.B. In Java, object destruction is implicit and automatic via

garbage collection

– Queries (state inspection), with return type

– Commands (state change), void

c© 2014, T. Verhoeff @ TUE.NL 20/34 Software Construction: Lecture 6

Page 21: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type: Specification of Semantics = Contract

• Set of (abstract) values

– given explicitly (through model variables; we do this), or

– given implicitly (through postulated properties of operations)

• Contracts for individual operations

– precondition, modifies clause, postcondition/returns, thrown

exceptions

• Public invariants : guaranteed relationships between queries

In Java, specification elements are stated in Javadoc comments

c© 2014, T. Verhoeff @ TUE.NL 21/34 Software Construction: Lecture 6

Page 22: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type: Implementation in Java

• Provide a private data representation for the type’s values,

and a representation invariant and abstraction function.

• For each operation, provide a method implementation

adhering to the contract.

c© 2014, T. Verhoeff @ TUE.NL 22/34 Software Construction: Lecture 6

Page 23: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Overview of ADT Specification & Implementation in Java

Specification: ...; Implementation: ___1 /** An ADTname object provides ...2 * model ...3 * @inv public invariant ...4 */5 public class ADTname {6 /** ___ private invariant ___ abstraction function ___ */7 private ___ ___;8

9 /** Constructs ... @pre ... @post ... */10 public ADTname() { ___ }11

12 /** Queries ... @pre ... @return ... */13 public ReturnType queryName(...) { ___; return ___; }14

15 /** Changes ... @pre ... @modifies ... @post ... */16 public void commandName(...) { ___ }17 }

c© 2014, T. Verhoeff @ TUE.NL 23/34 Software Construction: Lecture 6

Page 24: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type: Implementation

Data representation: is defined in terms of instance variables thatrepresent the intended abstract value.

class Fraction { private int numerator, denominator; ... }

Representation invariant: (short: rep invariant) condition to besatisfied by the instance variables, in order to make sense as a rep-resentation of an abstract value. Can be implemented in methodboolean isRepOk().

// rep inv I0: 0 < denominator

Abstraction function: maps each representation that satisfies therepresentation invariant to the represented abstract value. Canbe implemented (in some sense) in method String toString().

// AF(q) = q.numerator / q.denominator

c© 2014, T. Verhoeff @ TUE.NL 24/34 Software Construction: Lecture 6

Page 25: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Abstract Data Type: Usage in Java

• Declare variable: ADTname v = new ADTname(...);

E.g. Fraction f = new Fraction(1, 2), g = new Fraction(2, 3);

• Apply operations: ... v.operationName(...) ...,

in a state where the corresponding precondition holds

E.g. f.add(g)

c© 2014, T. Verhoeff @ TUE.NL 25/34 Software Construction: Lecture 6

Page 26: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Java Limitation

Unfortunately, in a Java class, specification and implementation are

combined into a single interleaved description.

Javadoc helps extract the specification.

Alternative: a Java interface defines a type without implementation

(Ch. 7.7).

An interface can contain only non-static, abstract, public methods.

A class can implement an interface through the keyword implements.

It extends only one other class, but can implement multiple interfaces.

Default: extends Object

c© 2014, T. Verhoeff @ TUE.NL 26/34 Software Construction: Lecture 6

Page 27: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Programs: Syntax and Semantics

• Syntax : What form can a program have?

Static aspect, independent of execution

Program text: should conform to the grammar of the program-

ming language

Program executable: in another language, generated by compiler

• Semantics : What is the meaning of a program

Dynamic aspect

Behavior, execution

c© 2014, T. Verhoeff @ TUE.NL 27/34 Software Construction: Lecture 6

Page 28: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Low-level (static, syntactic) Structure of a Java Program

Bottom-up view of Java program text:

• Bits , grouped into

• Unicode Characters , grouped into

• Lexical Tokens , forming

• Definitions , Declarations , Expressions , Statements , . . .

c© 2014, T. Verhoeff @ TUE.NL 28/34 Software Construction: Lecture 6

Page 29: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

High-level Static Structure of a Java Program

Program text (processed by Java compiler):

• Collection of .java text files ( compilation units )

• Organized in a containment hierarchy of packages

• Each file defines one or more classes or interfaces

• Each class defines (possibly static) variables and methods(later: also nested classes)

• One designated public static void main(String[]) method

Executable after compilation; run by Java Virtual Machine (JVM):

• Hierarchical collection of .class or .jar binary files

• One designated main entry method

c© 2014, T. Verhoeff @ TUE.NL 29/34 Software Construction: Lecture 6

Page 30: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Behavior: Different Views on State and State Change

State (of a computation):

• Memory contents

• Variables, each ‘having’ a value

• Abstract data

State change (also known as state transitions):

• Machine instructions, operating on the memory

• Statements, operating on the variables

• Actions/operations, operating on the abstract data

c© 2014, T. Verhoeff @ TUE.NL 30/34 Software Construction: Lecture 6

Page 31: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

State of a Running Java Program

• Collection of classes , and objects instantiated from classes

• Each variable holds a value of a primitive type or a reference to

an object, forming a labeled directed graph ( network of objects )

• Unreachable objects can be removed by the Garbage Collector

• Stack of nested method invocations (calls) that are active

At the bottom of the stack is the designated main method.

• Each active method invocation has parameters , local variables

and a current instruction address , together forming a stack frame

• Instruction at current address of topmost stack frame is executed

c© 2014, T. Verhoeff @ TUE.NL 31/34 Software Construction: Lecture 6

Page 32: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Programming techniques: General versus Java-specific

The aim of this course is to teach general programming techniques.

That is, techniques that are useful for many programming languages.

However, each programming language requires its own ‘mind set’

(often, that is why it was invented).

There is a danger that Java-specific matters take the upper hand.

Java details are hard to avoid:

• Concrete applications of techniques help to understand them.

• ‘Real’ programs are written in a concrete programming language.

c© 2014, T. Verhoeff @ TUE.NL 32/34 Software Construction: Lecture 6

Page 33: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Summary

• Java class can be used for

1. Library of static constants and methods (no state)

2. Defining an enumeration type : a set of related constants

3. Defining a record type : a labeled-product type

4. Defining an abstract data type (ADT)

• ADT encapsulates/hides the representation of the abstract dataand the implementation of operations on that data.

• It separates the use of and the implementation of a data type,through a specification in the form a of a two-sided contract.

• This allows modification of the implementation without requiringmodification of the using environment, and vice versa.

c© 2014, T. Verhoeff @ TUE.NL 33/34 Software Construction: Lecture 6

Page 34: Software Construction - TU/ewstomv/edu/sc-hse/downloads/Series_06/slides_06.pdf · Java class mechanism The class concept plays a central role in the Java programming language. It

Assignments Series 6

• Read Section 2.3.4 (Enums), and Chapter 5, Sections 5.1 and 5.2

in David Eck’s book

• See Checklist for Larger OO Programs

• Review your work for Series 5; improve where necessary/possible

• Compare immutable and mutable versions of Fraction

• Apply data abstraction in DiceGame

c© 2014, T. Verhoeff @ TUE.NL 34/34 Software Construction: Lecture 6