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.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Chapter 41 Defining Classes and Methods Chapter 4.
Intro to Java Part II. Calling an Objects Methods Use qualified names to call the objects methods. To form – you append the method name to an object reference.
CMT Programming Software Applications
Fundamental Programming Structures in Java: Strings.
Java An introduction. Example 1 public class Example1 { public static void main (String [] args) { System.out.println (“This is the first example”); int.
29-Jun-15 Using Objects. 2 Classes and objects The type of an object is the class that describes that object If we say int count, the type of count is.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Games and Simulations O-O Programming in Java The Walker School
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Java Classes Using Java Classes Introduction to UML.
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.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
A way to pull together related data A Shape Class would contain the following data: x, y, height, width Then associate methods with that data A Shape.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Classes CS 21a: Introduction to Computing I First Semester,
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Pictures Looping through pixels.. Lab Review (1) Objects  Instantiated from Class  Turtle myTut = new Turtle(myWorld);  new operator creates an instance.
CS61B L02 Using Objects (1)Garcia / Yelick Fall 2003 © UCB Kathy Yelick Handout for today: These lecture notes Computer Science 61B Lecture 2 – Using Objects.
3.1 Using Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
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.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
TOPIC 6 MODIFYING PICTURES USING LOOPS 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and.
Procedural programming in Java Methods, parameters and return values.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 2 - Using Objects.
Session 7 Methods Strings Constructors this Inheritance.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Working With Objects Tonga Institute of Higher Education.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Heads-Up – Programming Quiz This Week Announcement will be made via You will be provided with a login to the password-protected website You will.
Computer Science I Storing data. Binary numbers. Classwork/homework: Catch up. Do analysis of image types.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Guest Speaker - Cryptography Wednesday (Apr. 22) – Prof. abhi shelat.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
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.
The need for Programming Languages
Introduction to Computer Science / Procedural – 67130
Chapter 3: Using Methods, Classes, and Objects
Object Oriented Programming (OOP) LAB # 8
Looping through pixels.
3.1 Using Data Types With notes by Ron Cytron shown like this.
References Revisted (Ch 5)
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

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 blocks” n Usually single values. n Operations directly translate to machine instructions. OK, but we want to write programs that process other types of data. n Colors, pictures, strings, input streams, … n Complex numbers, vectors, matrices, polynomials, … n Points, polygons, charged particles, celestial bodies, … 2 Data Types OperationsSet of ValuesData Type not, and, or, xor true, false boolean double int add, subtract, multiplyany of 2 64 possible reals add, subtract, multiply to

Remember Abstraction? Hiding details…. One principle of “computational thinking.” When we use data types, keep these things in mind: n We don’t have to understand exactly how bits are stored in the machine. n We have an “information model” (or set of values), and… n We have operations to use -- even if we don’t know exactly how they’re implemented! Question for you: n If operations hide details and are a form of abstraction, can you think of something else we’ve done in Java that is also an example of this “procedural abstraction”? 3 Data Types and Abstraction

Reference type. n In Java, not a simple, basic data type. n Arrays are one kind of reference type. n Object types are another. – Examples: String, In n “Class” means data type that’s an object – Class and type. Object and variable. What’s important about reference types? n Object types are not part of the “core” language (perhaps part of standard libraries). Arrays are. n Object types can be defined by someone or by us. n The variable “refers to” or “points to” a separate chunk of memory. n We can access things inside what’s pointed to. – Example: int[] a = new int[10]; a.length – Problem: int[] b; b.length 4 “Non-primitive” types

5 Objects Object. Holds a value of a particular data-type. A variable name refers to an object. Class. The data type Impact. Enables us to create our own data types; define operations on them; and integrate into our programs. length, substring, comparesequence of characters String OperationsSet of ValuesData Type get red component, brighten24 bits Color Picture get/set color of pixel (i, j)2D array of colors

A Charge class. Represents a charged particle in a 2-dim space. Can use this to study “electric potential.” Data Model. n Location in a 2-dim space, so x and y values n The charge at that point Operations. n Calculate potential due to this particle as some other (x,y) n Convert this to a String for output An API defines functions (known as methods) for each class: n Charge (double x0, double y0, double q0) // constructor n double potentialAt( double x, double y) n String toString() 6 Example Data Type (Class): Charge

Note! No operators like +, *, etc. Methods / Functions. n These are slightly different than previous methods n These are “instance methods” n Previously we wrote “static” methods Instance methods are called “on” an object (a variable) n System.out.println(); // call println on System.out n String s = aCharge.toString(); // call toString on aCharge n In fileIn = new In(“file.txt”); fileIn.readInt(); Ways to think about this: n Send a message to an object. n Tell an object to do something. 7 Methods for a Class

In Java, remember: Variables must be initialized when created. We must have a way to make this happen for “new” types. One special instance method in the API: n Charge (double x0, double y0, double q0) // constructor n This is a method called when you invoke “new” to create a new object! n You can pass parameters to control initialization. n The class’ author defines the logic for this method to carry out proper initialization. 8 Constructors

9 Example: Constructors and Methods To construct a new object: Use keyword new and name of data type. To apply an operation: Use name of object, the dot operator, and the name of the method.

10 String Data Type String data type. Basis for text processing. Set of values. Sequence of Unicode characters. API. …

11 Typical String Processing Code

12

Image Processing

14 Color Data Type Color. A sensation in the eye from electromagnetic radiation. Set of values. [RGB representation] possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to G RColorB

15 Color Data Type Color. A sensation in the eye from electromagnetic radiation. Set of values. [RGB representation] possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255. API. Application Programming Interface.

16 Albers Squares Josef Albers. Revolutionized the way people think about color. Homage to the Square by Josef Albers ( )

17 % java AlbersSquares Albers Squares Josef Albers. Revolutionized the way people think about color.

18 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 = 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); } to access Color library first color second color first square second square

19 Monochrome Luminance Monochrome luminance. Effective brightness of a color. NTSC formula. Y = 0.299r g b. 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; }

20 Color Compatibility Q. Which font colors will be most readable with which background colors on computer monitors and cell phone screens? A. Rule of thumb: difference in luminance should be  128. public static boolean compatible(Color a, Color b) { return Math.abs(lum(a) - lum(b)) >= 128.0; }

21 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. Bottom line. We are writing programs that manipulate color. 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 int

22 Picture Data Type Raster graphics. Basis for image processing. Set of values. 2D array of Color objects (pixels). API. (0, 0) i j

23 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 i = 0; i < pic.width(); i++) { for (int j = 0; j < pic.height(); j++) { Color color = pic.get(i, j); Color gray = Luminance.toGray(color); pic.set(i, j, gray); } pic.show(); }

24 Image Processing: Grayscale Filter Goal. Convert color image to grayscale according to luminance formula. mandrill.jpg % java Grayscale mandrill.jpg

Horton got this far before Exam 2 in Spring For exam 2, no need to look at slides after this. Slides after this point will be covered after Exam 2. 25

26 Image Processing: Scaling Filter Goal. Shrink or enlarge an image to desired size. Downscaling. To shrink, delete half the rows and columns. Upscaling. To enlarge, replace each pixel by 4 copies.

27 Image Processing: Scaling Filter Goal. Shrink or enlarge an image to desired size. Uniform strategy. To convert from w s -by- h s to w t -by- h t : Scale row index by w s / w t. Scale column index by h s / h t. Set color of pixel (i, j) in target image to color of pixel (i  w s / w t, j  h s / h t ) in source image. ? source image ( w s -by- h s ) target image ( w t -by- h t ) i j i  ws / wti  ws / wt j  hs / htj  hs / ht

28 Image Processing: 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); } source.show(); target.show(); }

29 Image Processing: Scaling Filter Scaling filter. Creates two Picture objects and two windows. % java Scale mandrill.jpg mandrill.jpg

30 More Image Processing Effects (See book and book-site) wave filterglass filterSobel edge detection RGB color separation swirl filter

Objects and Reference Types: Important Issues See textbook: pp

32 Important Issues about Objects and Reference Types Study textbook: pages References are not objects! Aliases Comparing objects. Don’t use ==. Use.equals() Orphan objects, Memory Management

33 OOP Context for Color Possible memory representation. Object reference is analogous to variable name. n We can manipulate the value that it holds. n We can pass it to (or return it from) a method. 255 D0 0 D1 255 D2 D0 A0 magenta 0 D3 0 D4 0 D5 105 D6 105 D7 105 D8 D6 B0 gray memory address ("pointer")

34 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

35 References René Magritte. "This is not a pipe." Java. This is not a color. (Where “this” means c or sienna below.) OOP. Natural vehicle for studying abstract models of the real world. Color sienna = new Color(160, 82, 45); Color c = sienna.darker();

36 Reference variables and equality Remember arrays? Can’t use == to see if two have the same content. Objects. Same thing! Never use == if you want to know if they have the same content. Use instance method equals(). All Java classes should provide a working version of equals() that takes a 2 nd object as an argument. String s1 = new String("hello”); String s2 = new String("hello”); System.out.println( s1.equals(s2) ); true System.out.println( s1==s2 ); false System.out.println( s1==s1 ); true String s3 = s1; System.out.println( s1==s3 ); true

37 Some things can’t be changed: Color objects, for example Immutability. Can't change a Color object's value once created. Consequence. Don't need to worry about aliases. Color a = new Color(160, 82, 45); Color b = a; a = new Color(0, 0, 0); makes a point to a different Color, but does not change b no relevant methods in Color API

38 Java objects: Some are Immutable, Some are Not Immutability. Can't change a Color object's value once created. We can create a new color from an old one. We can change the Color object the reference points to. The String class is immutable too. Mutability. Can change a Picture object's value. Java has class StringBuffer that is like String but mutable. It has an append() method, for example. D0 D4 D8 DC Color red = new Color(255, 0, 0); pic.set(0, 3, red); no relevant methods in Color API

Code Example 39 public static void main (String[] args) { String s1 = "Defined in main."; changeString(s1); System.out.println("String obj is now: " + s1); // see? reference still points to original object StringBuffer sb1 = new StringBuffer("Defined in main."); changeStringBuffer(sb1); System.out.println("StringBuffer obj is now: " + sb1); // see? object pointed to has be changed! } public static void changeString(String s) { s = "Changed in method"; // change is only local } public static void changeStringBuffer(StringBuffer sb) { sb.append(" -- Changed in method"); }

40 Conclusion from Example Arguments that are object-references:  Code inside a method can change an argument passed to it. Only if that argument allows itself to be changed (i.e. is mutable).  Cannot make the object-reference point to a new object. In other words, inside the method: The thing “pointed to” can be changed. The “pointer” cannot be changed. This rule is same as for arrays!

41 OOP Summary Object. Holds a data type value; variable name refers to object. In Java, programs manipulate references to objects. Exception: primitive types, e.g., boolean, int, double. Reference types: String, Picture, Color, arrays, everything else. Bottom line. We wrote programs that manipulate colors, pictures, and strings. Next. We'll write programs that manipulate our own abstractions.

Extra Slides

43 Spectrum import java.awt.Color; public class Spectrum { public static void main(String[] args) { int N = Integer.parseInt(args[0]); Picture pic = new Picture(N, N); for (int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { int r = (i * 256) / N; int g = 128; int b = (j * 256) / N; Color c = new Color(r, g, b); pic.set(i, j, c); } pic.show(); pic.save("spectrum.png"); }

44 Java Function Involving Colors We can write Java functions that manipulate colors. n Ex: return convex combination of two colors. import java.awt.Color; public class ColorCombiner { public static Color combine(Color c1, Color c2, double beta) { int r = (int) (beta*c1.getRed() + (1-beta) * c2.getRed()); int g = (int) (beta*c1.getGreen() + (1-beta) * c2.getGreen()); int b = (int) (beta*c1.getBlue() + (1-beta) * c2.getBlue()); return new Color(r, g, b); } public static void main(String args[]) { Color c1 = new Color(127, 255, 255); Color c2 = new Color( 0, 127, 127); Color c3 = combine(c1, c2, 0.15); System.out.println("c3 = " + c3); } % java ColorCombiner c3 = java.awt.Color[r=19,g=146,b=146]

45 Color Separation import java.awt.Color; public class ColorSeparation { public static void main(String args[]) { Picture pic = new Picture(args[0]); int width = pic.width(); int height = pic.height(); Picture R = new Picture(width, height); Picture G = new Picture(width, height); Picture B = new Picture(width, height); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Color c = pic.get(i, j); int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); R.set(i, j, new Color(r, 0, 0)); G.set(i, j, new Color(0, g, 0)); B.set(i, j, new Color(0, 0, b)); } R.show(); G.show(); B.show(); }

46 Color Separation ColorSeparation.java. Creates three Picture objects and windows.

47 Image Processing: Swirl Filter Swirl.java. Creates two Picture objects and windows.

48 Image Processing: Swirl Filter Goal. Create swirl special effect by setting color of output pixel (i, j) to color of some other input pixel (ii, jj). double i0 = 0.5 * width; double j0 = 0.5 * height; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { double di = i - i0; double dj = j - j0; double r = Math.sqrt(di*di +dj*dj); double a = Math.PI / 256 * r; int ii = (int)(-di*Math.cos(a) + dj*Math.sin(a) + i0); int jj = (int)( di*Math.sin(a) + dj*Math.cos(a) + j0); if (ii >= 0 && ii = 0 && jj < height) pic2.set(i, j, pic1.get(ii, jj)); }

49 Memory Management Value types. n Allocate memory when variable is declared. n Can reclaim memory when variable goes out of scope. Reference types. Allocate memory when object is created with new. n Can reclaim memory when last reference goes out of scope. n Significantly more challenging if several references to same object. Garbage collector. System automatically reclaims memory; programmer relieved of tedious and error-prone activity.