9. Abstract Data Types, Study notes of Object Oriented Programming

A data type is a set of values and a set of operations on those values. An abstract data type is a data type whose representation is hidden from the client.

Typology: Study notes

2021/2022

Uploaded on 10/10/2022

yngve99
yngve99 🇸🇪

5

(2)

65 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
COMPUTER SCIENCE
SEDGEWICK/WAYNE
http://introcs.cs.princeton.edu
9. Abstract Data Types
Section 3.1
COMPUTER SCIENCE
SEDGEWICK/WAYNE
9. Abstract Data Types
Overview
Color
Image processing
String processing
CS.9.A.ADTs.Overview
Abstract data types
3
Primitive types
values immediately map to
machine representations
operations immediately map to
machine instructions.
A data type is a set of values and a set of operations on those values.
An abstract data type is a data type whose representation is hidden from the client.
We want to write programs that process
other types of data.
Colors, pictures, strings,
Complex numbers, vectors, matrices,
...
Object-oriented programming (OOP)
4
Object-oriented programming (OOP).
Create your own data types.
Use them in your programs (manipulate objects).
An abstract data type is a data type whose representation is hidden from the client.
Impact: We can use ADTs without knowing implementation details.
This lecture: how to write client programs for several useful ADTs
Next lecture: how to implement your own ADTs
data type
set of values
Color
three 8-bit integers
Picture
2D array of colors
String
sequence of characters
An object holds a data type value.
Variable names refer to objects.
Examples (stay tuned for details)
C
A
T
A
G
C
G
C
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download 9. Abstract Data Types and more Study notes Object Oriented Programming in PDF only on Docsity!

C O M P U T E R S C I E N C E

S E D G E W I C K / W A Y N E

h t t p : / / i n t r o c s. c s. p r i n c e t o n. e d u

9. Abstract Data Types

Section 3.

C O M P U T E R S C I E N C E

S E D G E W I C K / W A Y N E

9. Abstract Data Types

• Overview

• Color

• Image processing

• String processing

C S. 9. A. A D T s. O v e r v i e w

Abstract data types

Primitive types

  • values immediately map to

machine representations

operations immediately map to

machine instructions.

A data type is a set of values and a set of operations on those values.

An abstract data type is a data type whose representation is hidden from the client.

We want to write programs that process

other types of data.

Colors, pictures, strings,

  • Complex numbers, vectors, matrices,

...

Object-oriented programming (OOP)

Object-oriented programming (OOP).

Create your own data types.

  • Use them in your programs (manipulate objects ).

An abstract data type is a data type whose representation is hidden from the client.

Impact: We can use ADTs without knowing implementation details.

  • This lecture: how to write client programs for several useful ADTs

Next lecture: how to implement your own ADTs

data type set of values examples of operations

Color three 8-bit integers get red component, brighten

Picture 2D array of colors get/set color of pixel (i, j)

String sequence of characters length, substring, compare

An object holds a data type value.

Variable names refer to objects.

Examples (stay tuned for details)

C A T A G C G C

Sound

5

We have already been using ADTs!

public class StdAudio

void play(double[] a)

play the given sound wave

void save(String file, double[] a) save to a .wav file

double[] read(String file) read from a .wav file

Values: Array of doubles.

Operations: specified in API.

Representation: Hidden from user (.wav and other formats needed by devices).

Sound ADT

Strings

6

publicpublic classclass StringString

String(String s)

create a string with the same value

int length()

string length

char charAt(int i) ith character

String substring(int i, int j) ith through (j-1)st characters

boolean contains(String sub) does string contain sub_?_

boolean startsWith(String pre) does string start with pre_?_

boolean endsWith(String post) does string end with post_?_

int indexOf(String p) index of 1st occurrence of p

int indexOf(String p, int i)

index of 1st occurrence of p after i

String concat(String t)

this string with t appended

int compareTo(String t) string comparison

String replaceAll(String a,String b) result of changing a s to b s

String[] split(String delim) strings between occurrences of delim

boolean equals(String t) is this string's value the same as t 's

Operations (API)

Java's String ADT allows us to write Java

programs that manipulate strings.

A String is a sequence of Unicode characters.

defined in terms of its ADT values (typical)

stay tuned for more complete API later in this lecture

We have already been using ADTs!

Using a data type: constructors and methods

To use a data type, you need to know:

  • Its name (capitalized, in Java).

How to construct new objects.

  • How to apply operations to a given object.

To construct a new object

  • Use the keyword new to invoke a constructor.

Use data type name to specify type of object.

To apply an operation (invoke a method)

Use object name to specify which object.

  • Use the dot operator to indicate that an

operation is to be applied.

  • Use a method name to specify which operation.

String s;

s = new String ("Hello, World);

StdOut.println( s.substring(0, 5) );

new Building()

Pop quiz on ADTs

Q. What is an abstract data type?

Q. What is a data type?

A. A set of values and a set of operations on those values.

13

Color client example: Albers squares

public class AlbersSquares

public static void main(String[] args)

int r1 = Integer.parseInt(args[0]);

int g1 = Integer.parseInt(args[1]);

int b1 = Integer.parseInt(args[2]);

Color c1 = new Color(r1, g1, b1);

int r2 = Integer.parseInt(args[3]);

int g2 = Integer.parseInt(args[4]);

int b2 = Integer.parseInt(args[5]);

Color c2 = new Color(r2, g2, b2);

StdDraw.setPenColor(c1);

StdDraw.filledSquare(.25, .5, .2);

StdDraw.setPenColor(c2);

StdDraw.filledSquare(.25, .5, .1);

StdDraw.setPenColor(c2);

StdDraw.filledSquare(.75, .5, .2);

StdDraw.setPenColor(c1);

StdDraw.filledSquare(.75, .5, .1);

create first color

create second color

draw first pair

of squares

draw second pair

of squares

% java AlbersSquares 0 64 128 105 105 105

Computing with color: monochrome luminance

14

Def. The monochrome luminance of a color quantifies its effective brightness.

examplesexamplesexamplesexamplesexamplesexamplesexamplesexamples

red intensity

green intensity

blue intensity

color

luminance

Applications (next)

Choose colors for displayed text.

  • Convert colors to grayscale.

NTSC standard formula for luminance: 0.299r + 0.587g + 0.114b.

import java.awt.Color;

public class Luminance

public static double lum(Color c)

int r = c.getRed();

int g = c.getGreen();

int b = c.getBlue();

return .299r + .587g + .114*b;

public static void main(String[] args)

int r = Integer.parseInt(args[0]);

int g = Integer.parseInt(args[1]);

int b = Integer.parseInt(args[2]);

Color c = new Color(r, g, b);

StdOut.println(Math.round(lum(c)));

% java Luminance 0 64 128

52

Computing with color: compatability

Q. Which font colors will be most readable with which background colors on a display?

Rule of thumb. Absolute value of difference in luminosity should be > 128.

public static boolean compatible(Color a, Color b)

return Math.abs(lum(a) - lum(b)) > 128.0;

255 76 179 24

76 255 255 52

179 255 255 203

24 52 203 255

Computing with color: grayscale

Goal. Convert a colors to grayscale values.

Fact. When all three R, G, and B values are the same,

resulting color is on grayscale from 0 (black) to 255 (white).

Q. What value for a given color?

A. Its luminance!

public static Color toGray(Color c)

int y = (int) Math.round(lum(c));

Color gray = new Color(y, y, y);

return gray;

examplesexamplesexamplesexamplesexamplesexamplesexamplesexamples

red intensity

green intensity

blue intensity

color

luminance

grayscale

method for Luminance library

OOP context for color

17

Q. How does Java represent color? Three int values? Packed into one int value?

A. We don't know. The representation is hidden. It is an abstract data type.

An object reference is analogous to a variable name.

  • It is not the value but it refers to the value.

We can manipulate the value in the object it refers to.

  • We can pass it to (or return it from) a method.

Possible memory representation of red = new Color(255, 0, 0)

and gray = new Color(105, 105, 105);

105 105 105 x y 255 0 0

y red

memory

address

gray x

We also use object references to

invoke methods (with the. operator)

References and abstraction

18

René Magritte. This is not a pipe.

Java. These are not colors.

public static Color toGray(Color c)

int y = (int) Math.round(lum(c));

Color gray = new Color(y, y, y);

return gray;

Object-oriented programming. A natural vehicle for studying abstract models of the real world.

It is a picture of a painting of a pipe.

"This is not a pipe."

Surrealist computer scientist:

Neither is this.

% java RandomSeq 10000 | java Average

Yes it is! He's referring to the physical object he's holding.

Joke would be better if he were holding a picture of a pipe.

This is not a pipe.

C O M P U T E R S C I E N C E

S E D G E W I C K / W A Y N E

  1. Abstract Data Types
    • Overview
    • Color
    • Image processing
    • String processing

C S. 9. C. A D T s. I m a g e s

Pop quiz 1b on image processing

Q. What is the effect of the following code (not-so-easy question)?

25

Picture pic = new Picture(args[0]);

for (int i = 0; i < pic.width(); i++)

for (int j = 0; j < pic.height(); j++)

pic.set(i, pic.height()-j-1, pic.get(i, j));

pic.show();

Pop quiz 1c on image processing

Q. What is the effect of the following code?

26

Picture source = new Picture(args[0]);

int width = source.width();

int height = source.height();

Picture target = new Picture(width, height);

for (int i = 0; i < width; i++)

for (int j = 0; j < height; j++)

target.set(i, height-j-1, source.get(i, j));

target.show();

Picture client example: Scaling filter

Goal. Write a Java program to scale an image (arbitrarily and independently on x and y ).

Source: mandrill.jpg

300x

% java Scale mandrill.jpg 500 500

500x

% java Scale mandrill.jpg 600 200

600x

% java Scale mandrill.jpg 200 400

200x

99x

% java Scale mandrill.jpg 99 99

Picture client example: Scaling filter

Goal. Write a Java program to scale an image (arbitrarily and independently on x and y ).

Ex. Downscaling by halving.

Shrink in half by deleting

alternate rows and columns.

Ex. Upscaling by doubling.

Double in size by replacing

each pixel with four copies.

Picture client example: Scaling filter

29

Goal. Write a Java program to scale an image (arbitrarily and independently on x and y ).

A uniform strategy to scale from ws-by-hs to wt-by-ht.

Scale column index by ws/wt.

  • Scale row index by hs/ht.

ws

hs

wt

ht

row tj

column ti

Approach. Arrange computation to compute exactly one value for each target pixel.

row tj x hs/ht

column ti x ws/wt

30

Picture client example: Scaling filter

import java.awt.Color;

public class Scale

public static void main(String args[])

String filename = args[0];

int w = Integer.parseInt(args[1]);

int h = Integer.parseInt(args[2]);

Picture source = new Picture(filename);

Picture target = new Picture(w, h);

for (int ti = 0; ti < w; ti++)

for (int tj = 0; tj < h; tj++)

int si = ti * source.width() / w;

int sj = tj * source.height() / h;

Color color = source.get(si, sj);

target.set(ti, tj, color);

target.show();

% java Scale mandrill.jpg 300 900

More image-processing effects

wave filter glass filter Sobel edge detection

RGB color separation

swirl filter

C O M P U T E R S C I E N C E

S E D G E W I C K / W A Y N E

  1. Abstract Data Types
    • Overview
    • Color
    • Image processing
    • String processing

C S. 9. D. A D T s. S t r i n g s

37

String client example: Gene finding

public class GeneFind

public static void main(String[] args)

String start = args[0];

String stop = args[1];

String genome = StdIn.readAll();

int beg = -1;

for (int i = 0; i < genome.length() - 2; i++)

String codon = genome.substring(i, i+3);

if (codon.equals(start)) beg = i;

if (codon.equals(stop) && beg != -1 && beg+3 < i)

String gene = genome.substring(beg+3, i);

if (gene.length() % 3 == 0)

StdOut.println(gene);

beg = -1;

% more genomeTiny.txt

ATAGATGCATAGCGCATAGCTAGATGTGCTAGC

% java GeneFind ATG TAG < genomeTiny.txt

CATAGCGCA

TGC

Fixes bug in Program 3.1.

Pop quiz 1: What's the bug?

Pop quiz 2: Give input that causes

Program 3.1.8 to crash

OOP context for strings

38

Possible memory representation of

x 15 x+9 4 x+1 4

x

a a c a a g t t t a c a a g c

genome

memory

address

length

t s

Implications

  • s and t are different strings that share the same value "acaa".

(s == t) is false (because it compares addresses).

  • (s.equals(t)) is true (because it compares character sequences).

Java String interface is more complicated than the API (and not really an ADT).

String genome = "aacaagtttacaagc";

String s = genome.substring(1, 5);

String t = genome.substring(9, 13);

Object-oriented programming: summary

In Java, programs manipulate references to objects.

  • String, Picture, Color, arrays, (and everything else) are reference types.

Exceptions: boolean, int, double and other primitive types.

  • OOP purist: Languages should not have separate primitive types.

Practical programmer: Primitive types provide needed efficiency.

This lecture: You can write programs to manipulate sounds, colors, pictures, and strings.

Next lecture: You can define your own abstractions and write programs that manipulate them.

Object-oriented programming.

Create your own data types (sets of values and ops on them).

  • Use them in your programs (manipulate objects ).

An object holds a data type value.

Variable names refer to objects.

T A G A T G T G C T A G C

C O M P U T E R S C I E N C E

S E D G E W I C K / W A Y N E

h t t p : / / i n t r o c s. c s. p r i n c e t o n. e d u

9. Abstract Data Types

Section 3.