Using Data Types - Washington University in St. Louis

Download Report

Transcript Using Data Types - Washington University in St. Louis

Object (Class)
Introduction to Programming in Java: An Interdisciplinary Approach
·
Robert Sedgewick and Kevin Wayne
·
Copyright © 2002–2010
·
7/18/2015 6:36:53 AM
A Foundation for Programming
any program you might want to write
objects
create your own
data types
functions and modules
graphics, sound, and image I/O
arrays
conditionals and loops
Math
primitive data types
text I/O
assignment statements
2
Object Oriented Programming
Procedural programming. [verb-oriented]
Tell the computer to do this.
Tell the computer to do that.


OOP philosophy. Software is a simulation of the real world.
We know (approximately) how the real world works.
Design software to model the real world.


Objected oriented programming (OOP). [noun-oriented]
Programming paradigm based on data types.
Identify objects that are part of the problem domain or solution.
Identity: objects are distinguished from other objects (references).
State: objects know things (instance variables).
Behavior: objects do things (methods).





3
Object Oriented Programming
4
Alan Kay
Alan Kay. [Xerox PARC 1970s]
Invented Smalltalk programming language.
Conceived Dynabook portable computer.
Ideas led to: laptop, modern GUI, OOP.



“ The computer revolution hasn't started yet. ”
“ The best way to predict the future is to invent it. ”
“ If you don't fail at least 90 per cent of the time,
you're not aiming high enough. ”
Alan Kay
2003 Turing Award
— Alan Kay
5
Encapsulation
Bond. What's your escape route?
Saunders. Sorry old man. Section 26 paragraph 5, that
information is on a need-to-know basis only. I'm sure you'll
understand.
6
Intuition
Client
API
- volume
- change channel
- adjust picture
- decode NTSC signal
client needs to know
how to use API
Implementation
- cathode ray tube
- electron gun
- Sony Wega 36XBR250
- 241 pounds
implementation needs to know
what API to implement
Implementation and client need to
agree on API ahead of time.
7
Data Types
Data type. Set of values and operations on those values.
Primitive types. Values directly map to machine representation;
ops directly map to machine instructions.
Data Type
Set of Values
Operations
boolean
true, false
not, and, or, xor
int
-231 to 231 - 1
add, subtract, multiply
double
any of 264 possible reals
add, subtract, multiply
We want to write programs that process other types of data.
Colors, pictures, strings, input streams, …
Complex numbers, vectors, matrices, polynomials, …
Points, polygons, charged particles, celestial bodies, …



8
Encapsulation
Data type. Set of values and operations on those values.
Ex. int, String, Complex, Vector, Document, GuitarString, …
Encapsulated data type. Hide internal representation of data type.
Separate implementation from design specification.
Class provides data representation and code for operations.
Client uses data type as black box.
API specifies contract between client and class.



Bottom line. You don't need to know how a data type is implemented
in order to use it.
9
Intuition
Client
API
- volume
- change channel
- adjust picture
- decode NTSC signal
client needs to know
how to use API
Implementation
- cathode ray tube
- electron gun
- Sony Wega 36XBR250
- 241 pounds
implementation needs to know
what API to implement
Implementation and client need to
agree on API ahead of time.
10
Objects
Object-oriented programming.
Create your own data types (set of values and ops on them).
Use them in your programs (manipulate objects that hold values).


Data Type
Set of Values
Operations
Color
Three ints
get red component, brighten
Picture
2D array of Colors
get/set color of pixel (i, j)
String
sequence of chars
length, substring, compare
A class = a set of data
+
a set of methods operating on the data
A class is a complex, user-defined data type (as opposed to primitive
data types)
11
Intuition
Client
API
- volume
- change channel
- adjust picture
- decode NTSC signal
client needs to know
how to use API
Implementation
- gas plasma monitor
- Samsung FPT-6374
- wall mountable
- 4 inches deep
implementation needs to know
what API to implement
Can substitute better
implementation without changing the
client.
12
Image Processing
Using the Color Class
Color Data Type
Color. A sensation in the eye from electromagnetic radiation.
Set of values. [RGB representation] 2563 possible values, which quantify
the amount of red, green, and blue, each on a scale of 0 to 255.
R
G
B
255
0
0
0
255
0
0
0
255
255
255
255
0
0
0
255
0
255
105
105
105
Color
14
Color Data Type
Color. A sensation in the eye from electromagnetic radiation.
Set of values. [RGB representation] 2563 possible values, which quantify
the amount of red, green, and blue, each on a scale of 0 to 255.
API. Application Programming Interface. (predefined classes)
http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
15
Albers Squares
Josef Albers. Revolutionized the way people think about color.
Homage to the Square by Josef Albers (1949-1975)
16
Using Colors in Java
import java.awt.Color;
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 =
int g2 =
int b2 =
Color c2
Integer.parseInt(args[3]);
Integer.parseInt(args[4]);
Integer.parseInt(args[5]);
= 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);
first color
second color
first square
second square
}
}
17
Albers Squares
Josef Albers. Revolutionized the way people think about color.
blue
% java AlbersSquares 9 90 166
gray
100 100 100
18
Monochrome Luminance
Monochrome luminance. Effective brightness of a color.
NTSC formula. Y = 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 .299*r + .587*g + .114*b;
}
}
19
Color Compatibility
Q. Which font colors will be most readable with which background
colors on computer and cell phone screens?
A. Rule of thumb: difference in luminance should be  128.
255
208
105
47
28
14
public static boolean compatible(Color a, Color b) {
return Math.abs(lum(a) - lum(b)) >= 128.0;
}
20
Grayscale
Grayscale. When all three R, G, and B values are the same,
resulting color is on grayscale from 0 (black) to 255 (white).
Convert to grayscale. Use luminance to determine value.
public static Color toGray(Color c) {
int y = (int) Math.round(lum(c));
Color gray = new Color(y, y, y);
return gray;
}
round double to nearest long
Bottom line. We are writing programs that manipulate Color.
21
Picture Data Type
Raster graphics. Basis for image processing.
Set of values. 2D array of Color objects (pixels).
API.
22
Image Processing: Grayscale Filter
Goal. Convert color image to grayscale according to luminance formula.
import java.awt.Color;
public class Grayscale {
public static void main(String[] args) {
Picture pic = new Picture(args[0]);
for (int x = 0; x < pic.width(); x++) {
for (int y = 0; y < pic.height(); y++) {
Color color = pic.get(x, y);
Color gray = toGray(color);
pic.set(x, y, gray);
}
}
pic.show();
}
}
from before
23
Defining Classes in Java
To define a class, specify:
Set of values.
Operations defined on those values.


Java class. Defines a class by specifying:
Instance variables. (set of values)
Methods.
(operations defined on those values)
Constructors.
(create and initialize new objects)



24
Bank Account Class
Complex Numbers
Complex Number Data Type
Goal. Create a data type to manipulate complex numbers.
Set of values. Two real numbers: real and imaginary parts.
API.
a = 3 + 4i, b = -2 + 3i
a + b = 1 + 7i
a  b = -18 + i
|a|=5
27
Applications of Complex Numbers
Relevance. A quintessential mathematical abstraction.
Applications.
Fractals.
Impedance in RLC circuits.
Signal processing and Fourier analysis.
Control theory and Laplace transforms.
Quantum mechanics and Hilbert spaces.
…






28
Complex Number Data Type: Implementation
public class Complex {
private final double re;
private final double im;
instance variables
public Complex(double real, double imag) {
re = real;
im = imag;
}
constructor
public String toString() { return re + " + " + im + "i"; }
public double abs() { return Math.sqrt(re*re + im*im); }
public Complex plus(Complex b) {
double real = re + b.re;
double imag = im + b.im;
return new Complex(real, imag);
}
creates a Complex object,
and returns a reference to it
public Complex times(Complex b) {
double real = re * b.re – im * b.im;
double imag = re * b.im + im * b.re;
return new Complex(real, imag);
}
refers to b's instance variable
methods
}
29
Complex Number Data Type: A Simple Client
Client program. Uses data type operations to calculate something.
public static void main(String[] args) {
Complex a = new Complex( 3.0, 4.0);
Complex b = new Complex(-2.0, 3.0);
Complex c = a.times(b);
StdOut.println("a = " + a);
StdOut.println("b = " + b);
StdOut.println("c = " + c);
}
%
a
result of c.toString()
b
c
java TestClient
= 3.0 + 4.0i
= -2.0 + 3.0i
= -18.0 + 1.0i
30
Counter Data Type
Counter. Data type to count electronic votes.
public class Counter {
public int count;
public final String name;
public Counter(String id) { name = id;
}
public void increment()
{ count++;
}
public int value()
{ return count; }
}
Legal Java client.
Counter c = new Counter("Volusia County");
c.count = -16022;
Oops. Al Gore receives -16,022 votes in Volusia County, Florida.
31
Counter Data Type
Counter. Encapsulated data type to count electronic votes.
public class Counter {
private int count;
private final String name;
public Counter(String id) { name = id;
}
public void increment()
{ count++;
}
public int value()
{ return count; }
}
Does not compile.
Counter c = new Counter("Volusia County");
c.count = -16022;
Benefit. Can guarantee that each data type value remains
in a consistent state.
32
Changing Internal Representation
Encapsulation.
Keep data representation hidden with private access modifier.
Expose API to clients using public access modifier.


public class Complex {
private final double re, im;
public
public
public
public
public
Complex(double re, double im) { … }
double abs()
{ … }
Complex plus(Complex b)
{ … }
Complex times(Complex b)
{ … }
String toString()
{ … }
}
e.g., to polar coordinates
Advantage. Can switch internal representation without changing client.
Note. All our data types are already encapsulated!
33
Ask, Don't Touch
Encapsulated data types.
Don't touch data and do whatever you want.
Instead, ask object to manipulate its data.


"Ask, don't touch."
Adele Goldberg
Former president of ACM
Co-developed Smalltalk
Lesson. Limiting scope makes programs easier to maintain and understand.
"principle of least privilege"
34
Immutability
Immutability: Advantages and Disadvantages
Immutable data type. Object's value cannot change once constructed.
Advantages.
Makes program easier to debug.
Limits scope of code that can change values.
Pass objects around without worrying about modification.



Disadvantage. New object must be created for every value.
36
Final Access Modifier
Final. Declaring an instance variable to be final means that you can
assign it a value only once, in initializer or constructor.
public class Counter {
private final String name;
private int count;
...
}
this value doesn't change
once the object is constructed
this value changes by invoking
instance method
Advantages.
Helps enforce immutability.
Prevents accidental changes.
Makes program easier to debug.
Documents that the value cannot not change.




37
Spatial Vectors
Vector Data Type
Set of values. Sequence of real numbers. [Cartesian coordinates]
API.
x = (0, 3, 4, 0), y = (0, -3, 1, -4)
x + y = (0, 0, 5, -4)
3x = (0, 9, 12, 0)
x
y = (0
0) + (3
-3) + (4
1) + (0
-4) = -5
| x | = (02 + 32 + 42 + 02)1/2 = 5
x = x / | x | = (0, 0.6, 0.8, 0)
39
Vector Data Type Applications
Relevance. A quintessential mathematical abstraction.
Applications.
Statistics.
Linear algebra.
Clustering and similarity search.
Force, velocity, acceleration, momentum, torque.
…





40
Vector Data Type: Implementation
public class Vector {
private int N;
private double[] coords;
instance variables
public Vector(double[] a) {
N = a.length;
coords = new double[N];
for (int i = 0; i < N; i++)
coords[i] = a[i];
}
constructor
public double dot(Vector b) {
double sum = 0.0;
for (int i = 0; i < N; i++)
sum += (coords[i] * b.coords[i]);
return sum;
}
public Vector plus(Vector b) {
double[] c = new double[N];
for (int i = 0; i < N; i++)
c[i] = coords[i] + b.coords[i];
return new Vector(c);
}
methods
41
Vector Data Type: Implementation
public Vector times(double t) {
double[] c = new double[N];
for (int i = 0; i < N; i++)
c[i] = t * coords[i];
return new Vector(c);
}
public double magnitude() {
return Math.sqrt(this.dot(this));
}
public Vector direction() {
return this.times(1.0 / this.magnitude());
}
...
This. The keyword this is a reference to the invoking object.
Ex. When you invoke a.magnitude(), this is an alias for a.
42