3.2 Creating Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · January.

Slides:



Advertisements
Similar presentations
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Advertisements

3.4 N-body Simulation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause.
References and Objects Weiss ch. 2. Objects Are structured regions of memory –Reside in heap Each object is an instance of a type –e.g. String, File,
Enhancing classes Visibility modifiers and encapsulation revisited
Games and Simulations O-O Programming in Java The Walker School
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Designing Data Types. 2 Object Oriented Programming Procedural programming. [verb-oriented] n Tell the computer to do this. n Tell the computer to do.
3.3 Designing Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · September.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
3.1 Data Types: Using Objects. Data type. Set of values and operations on those values. Primitive types. n “Built-in” for a language. Basic “building.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
CS177 RECITATION WEEK 7 Input and Output (Text & Graphical)
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 9/10/08 9/10/08.
Introducing Objects and stuff GABY and MATT Definition: Object: “a class that is the root of the hierarchy tree for all classes in JAVA.” –An object.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC 142 Computer Science II Zhen Jiang West Chester University
CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
Chapter 4 Introduction to Classes, Objects, Methods and strings
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
File Input and Graphics An extract of slides from set 05_inout.ppt Designed to get you ready for the HW3.
1.2 Built-in Types of Data Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
Computer Science I Classes and objects Classwork/Homework: Examine and modify my examples. Make your own.
Non-static classes 1.  a utility class has features (fields and methods) that are all static  all features belong to the class  therefore, you do not.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Week 10 - Friday.  What did we talk about last time?  References and primitive types  Started review.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University.
Object Oriented Programming Lecture 2: BallWorld.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CS 112 Introduction to Programming User-Defined Data Types: OOP Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
3.1 Objects. Data type. Set of values and operations on those values. Primitive/Built-In types. n Usually single values n Can build arrays but they can.
Chapter 9 Objects and Classes Chapter 10 Object-Oriented Thinking
Objects as a programming concept
Building Java Programs
CSC240 Computer Science III
Object Oriented Programming (OOP) LAB # 8
Building Java Programs
Building Java Programs
Programs and Classes A program is made up from classes
3.2 Creating Data Types With notes by Ron Cytron shown like this.
Java Programming Language
1.5 Input and Output Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 2/14/11.
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Introduction to Computer Science I.
Building Java Programs
Presentation transcript:

3.2 Creating Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · January 7, :07 tt

2 Data Types Data type. Set of values and operations on those values. Basic types. Last time. Write programs that use data types. Today. Write programs to create our own data types. Some OperationsSet of ValuesData Type not, and, or, xor true, false boolean String int concatenate, comparesequence of Unicode characters add, subtract, multiply to

3 Defining Data Types in Java To define a data type, specify: n Set of values. n Operations defined on those values. Java class. Defines a data type by specifying: n Instance variables. (set of values) n Methods. (operations defined on those values) n Constructors. (create and initialize new objects)

4 Point Charge Data Type Goal. Create a data type to manipulate point charges. Set of values. Three real numbers. [position and electrical charge] Operations. Create a new point charge at (r x, r y ) with electric charge q. Determine electric potential V at (x, y) due to point charge. n Convert to string. r = distance between (x, y) and (r x, r y ) k = electrostatic constant = 8.99  10 9 N  m 2 / C 2 q

5 Point Charge Data Type Goal. Create a data type to manipulate point charges. Set of values. Three real numbers. [position and electrical charge] API.

6 Charge Data Type: A Simple Client Client program. Uses data type operations to calculate something. public static void main(String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); Charge c1 = new Charge(.51,.63, 21.3); Charge c2 = new Charge(.13,.94, 81.9); double v1 = c1.potentialAt(x, y); double v2 = c2.potentialAt(x, y); StdOut.println(c1); StdOut.println(c2); StdOut.println(v1 + v2); } % java Charge at (0.51, 0.63) 81.9 at (0.13, 0.94) e12 automagically invokes the toString() method

7 Anatomy of Instance Variables Instance variables. Specifies the set of values. n Declare outside any method. Always use access modifier private. Use modifier final with instance variables that never change. stay tuned

8 Anatomy of a Constructor Constructor. Specifies what happens when you create a new object. Invoking a constructor. Use new operator to create a new object.

9 Anatomy of a Data Type Method Method. Define operations on instance variables. Invoking a method. Use dot operator to invoke a method. object name invoke method

10 Anatomy of a Class

11 Potential Visualization Potential visualization. Read in N point charges from a file; compute total potential at each point in unit square. % more charges.txt % java Potential < charges.txt

12 Potential Visualization Arrays of objects. Allocate memory for the array; then allocate memory for each individual object. // read in the data int N = StdIn.readInt(); Charge[] a = new Charge[N]; for (int i = 0; i < N; i++) { double x0 = StdIn.readDouble(); double y0 = StdIn.readDouble(); double q0 = StdIn.readDouble(); a[i] = new Charge(x0, y0, q0); }

13 Potential Visualization // plot the data int SIZE = 512; Picture pic = new Picture(SIZE, SIZE); for (int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { double V = 0.0; for (int i = 0; i < N; i++) { double x = 1.0 * row / SIZE; double y = 1.0 * col / SIZE; V += a[i].potentialAt(x, y); } Color color = getColor(V); pic.set(row, SIZE-1-col, color); } pic.show(); (0, 0) is upper left compute color as a function of potential V

Turtle Graphics

15 Turtle Graphics Goal. Create a data type to manipulate a turtle moving in the plane. Set of values. Location and orientation of turtle. API. // draw a square Turtle turtle = new Turtle(0.0, 0.0, 0.0); turtle.goForward(1.0); turtle.turnLeft(90.0); turtle.goForward(1.0); turtle.turnLeft(90.0); turtle.goForward(1.0); turtle.turnLeft(90.0); turtle.goForward(1.0); turtle.turnLeft(90.0);

16 Turtle Graphics public class Turtle { private double x, y; // turtle is at (x, y) private double angle; // facing this direction public Turtle(double x0, double y0, double a0) { x = x0; y = y0; angle = a0; } public void turnLeft(double delta) { angle += delta; } public void goForward(double d) { double oldx = x; double oldy = y; x += d * Math.cos(Math.toRadians(angle)); y += d * Math.sin(Math.toRadians(angle)); StdDraw.line(oldx, oldy, x, y); }

17 N-gon public class Ngon { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double angle = / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < N; i++) { turtle.goForward(step); turtle.turnLeft(angle); }

18 Spira Mirabilis public class Spiral { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double decay = Double.parseDouble(args[1]); double angle = / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < 10 * N; i++) { step /= decay; turtle.goForward(step); turtle.turnLeft(angle); }

19 Spira Mirabilis in Nature

Complex Numbers

21 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 = i a + b = 1 + 7i a  b = i | a | = 5

22 Applications of Complex Numbers Relevance. A quintessential mathematical abstraction. Applications. n Fractals. n Impedance in RLC circuits. n Signal processing and Fourier analysis. n Control theory and Laplace transforms. n Quantum mechanics and Hilbert spaces. n …

23 Complex Number Data Type: A Simple Client Client program. Uses data type operations to calculate something. Remark. Can't write a = b*c since no operator overloading in Java. 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); } % java TestClient a = i b = i c = i result of c.toString()

24 Complex Number Data Type: Implementation public class Complex { private final double re; private final double im; public Complex(double real, double imag) { re = real; im = imag; } 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); } 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); } constructor instance variables methods creates a Complex object, and returns a reference to it refers to b's instance variable

25 Mandelbrot Set Mandelbrot set. A set of complex numbers. Plot. Plot (x, y) black if z = x + y i is in the set, and white otherwise. n No simple formula describes which complex numbers are in set. n Instead, describe using an algorithm.

26 Mandelbrot Set Mandelbrot set. Is complex number z 0 is in set? Iterate z t + 1 = (z t ) 2 + z 0. If | z t | diverges to infinity, then z 0 not in set; otherwise z 0 is in set. z = 1 + i not in Mandelbrot set z = -1/2 is in Mandelbrot set -1/2 + 0i0 -1/4 + 0i1 -7/16 + 0i2 -79/ i / i / i ztzt 5 t 1 + i i i i – 193i i ztzt 5 t

27 Plotting the Mandelbrot Set Practical issues. n Cannot plot infinitely many points. n Cannot iterate infinitely many times. Approximate solution. Sample from an N -by- N grid of points in the plane. Fact: if | z t | > 2 for any t, then z not in Mandelbrot set. Pseudo-fact: if | z 255 |  2 then z "likely" in Mandelbrot set i 8-by-8 grid (-1.5, -1) (0.5, 1)

28 Complex Number Data Type: Another Client Mandelbrot function with complex numbers. Is z in the Mandelbrot set? n Returns white (definitely no) or black (probably yes). More dramatic picture: replace Color.WHITE with grayscale or color. public static Color mand(Complex z0) { Complex z = z0; for (int t = 0; t < 255; t++) { if (z.abs() > 2.0) return Color.WHITE; z = z.times(z); z = z.plus(z0); } return Color.BLACK; } z = z 2 + z 0 new Color(255-t, 255-t, 255-t)

29 Complex Number Data Type: Another Client Plot the Mandelbrot set in gray scale. public static void main(String[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); int N = 512; Picture pic = new Picture(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/N; double y0 = yc - size/2 + size*j/N; Complex z0 = new Complex(x0, y0); Color color = mand(z0); pic.set(i, N-1-j, color); } pic.show(); } scale to screen coordinates (0, 0) is upper left

30 Mandelbrot Set % java Mandelbrot –.5 0 2% java Mandelbrot

31 Mandelbrot Set % java ColorMandelbrot – < mandel.txt

32

33 Mandelbrot Set (-1.5, -1)

34 Applications of Data Types Data type. Set of values and collection of operations on those values. Simulating the physical world. n Java objects model real-world objects. n Not always easy to make model reflect reality. n Ex: charged particle, molecule, COS 126 student, …. Extending the Java language. n Java doesn't have a data type for every possible application. n Data types enable us to add our own abstractions. n Ex: complex, vector, polynomial, matrix,....

35 Mandelbrot Set Music Video Set

3.2 Extra Slides

37 Example: Bouncing Ball in Unit Square Bouncing ball. Model a bouncing ball moving in the unit square with constant velocity.

38 Example: Bouncing Ball in Unit Square public class Ball { private double rx, ry; private double vx, vy; private double radius; public Ball() { rx = ry = 0.5; vx = Math.random() * 0.03; vy = Math.random() * 0.03; radius = Math.random() * 0.01; } public void move() { if ((rx + vx > 1.0) || (rx + vx < 0.0)) vx = -vx; if ((ry + vy > 1.0) || (ry + vy < 0.0)) vy = -vy; rx = rx + vx; ry = ry + vy; } public void draw() { StdDraw.filledCircle(rx, ry, radius); } instance variables Ball.java bounce constructor methods

39 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C00 C10 C20 C30 C40 C50 C60 C70 C80 C90 CA0 CB0 CC0 addrvalue

40 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C00 C10 C20 C30 C40 C50 C60 C70 C80 C90 CA0 CB0 CC0 C0 registers addrvalue b1

Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C0 C1 C2 C3 C40.03 C50 C60 C70 C80 C90 CA0 CB0 CC0 C0 registers addrvalue b1

42 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C00.55 C10.51 C20.05 C30.01 C40.03 C50 C60 C70 C80 C90 CA0 CB0 CC0 C0 registers addrvalue b1

43 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C00.60 C10.52 C20.05 C30.01 C40.03 C50 C60 C70 C80 C90 CA0 CB0 CC0 C0 registers C addrvalue b1 b2

44 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C00.60 C10.52 C20.05 C30.01 C40.03 C50 C60 C70.50 C80.50 C90.07 CA0.04 CB0.04 CC0 C7 registers C addrvalue b1 b2

45 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C00.60 C10.52 C20.05 C30.01 C40.03 C50 C60 C70.57 C80.54 C90.07 CA0.04 CB0.04 CC0 C0 Data stored in C7 – CB for abstract bit recycler. registers C0 addrvalue b1 b2

46 Object References Object reference. n Allow client to manipulate an object as a single entity. n Essentially a machine address (pointer). Ball b1 = new Ball(); b1.move(); Ball b2 = new Ball(); b2.move(); b2 = b1; b2.move(); main memory (64-bit machine) C0 addr 0.60 value C10.52 C20.05 C30.01 C40.03 C50 C60 C70.57 C80.54 C90.07 CA0.04 CB0.04 CC0 C0 b1 Moving b2 also moves b1 since they are aliases that reference the same object. registers C0 b

47 Creating Many Objects Each object is a data type value. Use new to invoke constructor and create each one. n Ex: create N bouncing balls and animate them. public class BouncingBalls { public static void main(String[] args) { int N = Integer.parseInt(args[0]); Ball balls[] = new Ball[N]; for (int i = 0; i < N; i++) balls[i] = new Ball(); while(true) { StdDraw.clear(); for (int i = 0; i < N; i++) { balls[i].move(); balls[i].draw(); } StdDraw.show(20); } create and initialize N objects animation loop

48 50 Bouncing Balls % java BouncingBalls 50 Color. Associate a color with each ball; paint background black. Scientific variations. Account for gravity, spin, collisions, drag, …

49 OOP Context Reference. Variable that stores the name of a thing. Some consequences. n Assignment statements copy references (not objects). The == operator tests if two references refer to same object. n Pass copies of references (not objects) to functions. – efficient since no copying of data – function can change the object 00FACADE Byte of computer memory NameThing 1C Word of TOY memory Web page Bank account 35 Olden Street Home

50 Using a Data Type in Java Client. A sample client program that uses the Point data type. public class PointTest { public static void main(String[] args) { Point a = new Point(); Point b = new Point(); double distance = a.distanceTo(b); StdOut.println("a = " + a); StdOut.println("b = " + b); StdOut.println("distance = " + distance); } % java PointTest a = ( , ) b = ( , ) distance =

51 Points in the Plane Data type. Points in the plane. dx dy a b public class Point { private double x; private double y; public Point() { x = Math.random(); y = Math.random(); } public String toString() { return "(" + x + ", " + y + ")"; } public double distanceTo(Point p) { double dx = x - p.x; double dy = y - p.y; return Math.sqrt(dx*dx + dy*dy); }

52 public class Circle { private Point center; private double radius; public Circle(Point center, double radius) { this.center = center; this.radius = radius; } public boolean contains(Point p) { return p.dist(center) <= radius; } public double area() { return Math.PI * radius * radius; } public boolean intersects(Circle c) { return center.dist(c.center) <= radius + c.radius; } A Compound Data Type: Circles Goal. Data type for circles in the plane. center p

53 Pass-By-Value Arguments to methods are always passed by value. n Primitive types: passes copy of value of actual parameter. n Objects: passes copy of reference to actual parameter. public class PassByValue { static void update(int a, int[] b, String c) { a = 7; b[3] = 7; c = "seven"; StdO.println(a + " " + b[3] + " " + c); } public static void main(String[] args) { int a = 3; int[] b = { 0, 1, 2, 3, 4, 5 }; String c = "three"; StdOut.println(a + " " + b[3] + " " + c); update(a, b, c); StdOut.println(a + " " + b[3] + " " + c); } % java PassByValue 3 3 three 7 7 seven 3 7 three