! Theoretical examples: ! Examples from Java: ! data type: A category of data values. " Example: integer, real number, string

Similar documents
References and objects

Building Java Programs

Building Java Programs

APCS++ Object-oriented programming

AP Computer Science. Classes and Objects

Building Java Programs

Lecture 11: Intro to Classes

Building Java Programs

Topic 27 classes and objects, state and behavior

Building Java Programs Chapter 8

A programming problem. Building Java Programs Chapter 8. Observations. A bad solution. Classes

Building Java Programs

Value vs. reference semantics

Parameters. Repetitive figures. A solution? Parameterization. Declaring parameterized methods. Generalizing methods. Readings: 3.1

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts

Fundamentals of Programming Data Types & Methods

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Arrays. Eng. Mohammed Abdualal

CS 211: Methods, Memory, Equality

Object Oriented Programming. Java-Lecture 6 - Arrays

Example: Monte Carlo Simulation 1

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Programming with Java

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

H212 Introduction to Software Systems Honors

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

JAVA Ch. 4. Variables and Constants Lawrenceville Press

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

PROGRAMMING FUNDAMENTALS

Package. A package is a set of related classes Syntax to put a class into a package: Two rules: Example:

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Lecture 12: Classes II

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CS 455 Midterm Exam 1 Fall 2013 [Bono] Wednesday, Oct. 2, 2013

CSE 143 Lecture 3. More ArrayList; object-oriented programming. reading: 10.1;

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Lecture Set 2: Starting Java

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Controls Structure for Repetition

Lecture Set 2: Starting Java

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

CS 231 Data Structures and Algorithms, Fall 2016

RECURSION (CONTINUED)

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Midterm Examination (MTA)

CIS 110: Introduction to Computer Programming

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

CS 1302 Chapter 9 (Review) Object & Classes

Introduction to Java & Fundamental Data Types

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Array. Array Declaration:

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Remedial classes. G51PRG: Introduction to Programming Second semester Lecture 2. Plan of the lecture. Classes and Objects. Example: Point class

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

Java Classes: Math, Integer A C S L E C T U R E 8

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Give one example where you might wish to use a three dimensional array

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Java Basic Programming Constructs

Loops. CSE 114, Computer Science 1 Stony Brook University

Selected Questions from by Nageshwara Rao

Java Programming Language. 0 A history

12/2/2009. The plan. References. References vs. pointers. Reference parameters. const and references. HW7 is out; new PM due date Finish last lecture

Chapter 2: Basic Elements of Java

CSE 114 Computer Science I

4. Java language basics: Function. Minhaeng Lee

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

CMSC131. Introduction to your Introduction to Java. Why Java?

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Chapter 4: Control Structures I

Oct Decision Structures cont d

Computational Expression

CSE 142 Su 04 Computer Programming 1 - Java. Objects

c) And last but not least, there are javadoc comments. See Weiss.

Chapter 6 Classes and Objects

Data Structure and Programming Languages

Chapters 1-4 Summary. Syntax - Java or C? Syntax - Java or C?

I. Variables and Data Type week 3

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

CS 455 Midterm Exam 1 Spring 2015 [Bono] Thursday, Feb. 19, 2015

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Tutorial 03. Exercise 1: CSC111 Computer Programming I

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction to Java Unit 1. Using BlueJ to Write Programs

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Transcription:

Object types Example object types! So far, we have seen: ( types " variables, which represent data (categorized by " methods, which represent behavior! object: An variable that contains data and behavior. " There are variables inside the object, representing its data. " There are methods inside the object, representing its behavior.! class: ( far " Basic building block of Java programs (what we have seen so AND " Data types for objects! Theoretical examples: " A class Person could represent objects that store a name, height, weight, hair color, IQ, etc! " A class Laptop could represent objects that store speed, screen size, color, dimensions, brand, etc!! Examples from Java: " The class String represents objects that store text characters. " The class Scanner represents objects that can tokenize streams of characters. 3 4 Recall: Data types Objects! data type: A category of data values. " Example: integer, real number, string 1! Java data types are divided into two sets: " primitive types: Java's 8 built-in simple data types for numbers, text characters, and logic.! boolean, char, byte, short, int, long, float, double " object types: All other types!! e.g., Scanner, System, String, Math 2

Constructing objects Point object: Construction! construct: To create a new object. " Objects are constructed with the new keyword.! Constructing objects, general syntax: <class> <name> = new <class>(<arguments>); Point p = new Point(7, -4); Scanner console = new Scanner(System.in);! Constructing a Point object, general syntax: Point <name> = new Point(<x>, <y>); Point <name> = new Point(); // the origin, (0, 0)! Point p1 = new Point(5, -2); Point p2 = new Point();! Q: Wait a minute! Why don!t we construct strings with new?! A1: Strings are one of the most commonly used objects, so they have special syntax (quotation marks) to simplify their construction.! A2: Also, you can if you want to: String s = new String("hi#); 7 8 Point object Point objects! Data stored in each Point object: Field name Description x the point's x-coordinate y the point's y-coordinate! Useful methods in each Point object: Method name Description distance(p)! how far away the point is from point p setlocation(x, sets the point's x and y to the given values translate(dx, y)! dy)! adjusts the point's x and y by the given amounts 5 6

References! Object variables are references to the location in memory where their data resides.! We draw references as pointers.! Actually, p stores the address of the location in memory where its data is. Fields Constructing an object! What happens when the following call is made? Point p1 = new Point(7, 2); p1: x: 7 y: 2 Variable, with slot in memory p: Reference, a pointer to the object s data x: y: 7 3 Data, in another part of memory 12 Representing objects Representing objects! So far, I have drawn primitive types like this:! I will represent object types like this: int x = 7; Point p = new Point(7,3); Fields X: 7 Variable, with slot in memory p: Reference, a pointer to the object s data x: y: 7 3 Data, in another part of memory

Calling methods on objects Dereferencing! Since the methods are bundled in the objects, calling these methods requires specifying which object we are talking to.! Calling a method of an object, general syntax: <variable>.<method name>(<parameters>)! " The results may vary from one object to another. Point p0 = new Point(0, 0); Point p1 = new Point(7, 3); Point p2 = new Point(2, -2); System.out.println(p1.distance(p0)); // 7.62 System.out.println(p2.distance(p0)); // 2.83! When we use the. operator on an object, we access the stuff (methods and/or data) that the object references (or points to).! This is called dereferencing.! The. operator is the dereferencing operator. 15 null objects Calling methods on objects! null is a value for all object types that says,!this object is a reference to nothing at all"! We draw null objects with a slash! Note that null objects have no memory reserved for their data! Point p1 = null; p1:! Since the methods are bundled in the objects, calling these methods requires specifying which object we are talking to.! Calling a method of an object, general syntax: <variable>.<method name>(<parameters>)! " The results may vary from one object to another. String s1 =!Homey da Clown"; String s2 =!Bubbles the clown"; System.out.println(s1.length()); // prints 14 System.out.println(s2.length()); // prints 17 13 14

Using Point objects: Example import java.awt.*; public class PointMain { public static void main(string[] args) { // construct two Point objects Point p1 = new Point(7, 2); Point p2 = new Point(4, 3); To use the Point class, you have to import it from the java.awt package in Java. // print each point and their distance apart System.out.println("p1 is " + p1); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2)); Using Point objects: Exercise! Write a program ComputePerimeter that computes a right triangle's perimeter given two integer side lengths (a and b). " The perimeter is the sum of the triangle's side lengths a+b+c.! Example: Given side lengths of 12 and 5, the program should display a perimeter of 30. // translate the point to a new location p2.translate(1, 7); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2)); 19 20 Three kinds of method calls Fields Type:! We have seen three ways to call methods: When it s used: For methods defined in the same class as they re called No. used <class>.<method> <variable>.<method> For static methods defined in another class For non-static or instance methods defined in another class Examples: mymethod(); Math.max(a,b) mystring.length() Integer.parseInt( 6 ) console.nextint() Server.gcd(15,12) mypoint.translate(2,2)! Fields are variables that contain data for an object.! Since the fields are bundled in the objects, referring to fields requires specifying an object.! Referring to the field of an object, general syntax: <variable>.<field name> Point p = new Point(7, 3); // p = (7,3) p.x = 2; // p = (2,3) p.y = p.y + 10; // p = (2,13) // displays!(2, 13)" System.out.println(!(! + p.x +!,! + p.y +!)");

Big idea: Abstraction Classes and objects! abstraction: A distancing between ideas and details. " How do objects provide a level of abstraction? 23! You use abstraction every day! " Do YOU know how your ipod works?????? 24 Using Point objects: Solution Common Programming Error import java.util.scanner; public class ComputePerimeter { public static void main(string [] args) { Scanner input = new Scanner(System.in); System.out.println(!enter coordinates for point 1:"); int x1 = input.nextint(), y1 = input.nextint(); System.out.println(!enter coordinates for point 2:"); int x2 = input.nextint(), y2 = input.nextint();! The dreaded NullPointerException Point p = null; p.x = 7; // Error! p.setlocation(0,0); // Error! Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double c = p1.distance(p2); System.out.println(!perimeter =! + (a + b + c)); 21! If you try to dereference a null object, it will cause a NullPointerException. Why?! This is a very common error, but one nice thing about Java is that it is often fairly easy to fix this kind of error (in my experience).

Recall: Point class Point class Point class! Data stored in each Point object: Field name Description x the point's x-coordinate y the point's y-coordinate int x, y distance(point p) equals(point p) setlocation(int x, int y) tostring() ( dy translate(int dx, int! Useful methods in each Point object: Method name Description distance(p)! how far away the point is from point p setlocation(x, sets the point's x and y to the given values translate(dx, y)! dy)! adjusts the point's x and y by the given amounts Point object #1 int x, y distance(point p) equals(point p) setlocation(int x, int y) tostring() ( dy translate(int dx, int Point object #2 int x, y distance(point p) equals(point p) setlocation(int x, int y) tostring() ( dy translate(int dx, int Point object #3 int x, y distance(point p) equals(point p) setlocation(int x, int y) tostring() ( dy translate(int dx, int 27 28 Classes are like blueprints Recall: Point class Music player blueprint Music player #1 station/song, volume, battery life power on/off change station/song change volume choose random song station/song, volume, battery life power on/off change station/song change volume choose random song Music player #2 station/song, volume, battery life power on/off change station/song change volume choose random song Music player #3 station/song, volume, battery life power on/off change station/song change volume choose random song! Constructing a Point object, general syntax: Point <name> = new Point(<x>, <y>); Point <name> = new Point(); // the origin, (0, 0)! Point p1 = new Point(5, -2); Point p2 = new Point(); 25 26

Recall: Value semantics Reference semantics! value semantics: Behavior where variables are copied when assigned to each other or passed as parameters. " Primitive types in Java use value semantics. " Modifying the value of one variable does not affect other.! Example: int x = 5; int y = x; // x = 5, y = 5 y = 17; // x = 5, y = 17 x = 8; // x = 8, y = 17! reference semantics: Behavior where variables refer to a common value when assigned to each other or passed as parameters. " Object types in Java use reference semantics. " Object variables do not store an object; they store the address of an object's location in the computer memory. We graphically represent addresses as arrows.! Example: Point p1 = new Point(3, 8); p1 x: 3 y: 8 31 32 instances! Definition: An object is an instance of its class. Value vs. reference semantics! Each instance has its own local copy of the state and behavior defined in the class template.! Example: each Point object has its own x,y coordinates, and its own setlocation method. 30

Reference semantics: Example Reference semantics: Example Point p1 = new Point(3, 8); Point p2 = new Point(2, -4); Point p3 = p2;! How many unique objects are there? How do you know that? " Two, because objects are only created with the new keyword.! If we change p3, will p2 be affected and vice versa? " Yes. p1 x: 3 y: 8! If two variables refer to the same object, modifying one of them will also make a change in the other: p3.translate(5, 1); System.out.println("(" + p2.x + " " + p2.y + ")"); p1 p2 x: x: 3 72 y: y: 8-3 -4 p2 p3 x: 2 y: -4 Output:!)3-,7( p3 35 36 Reference semantics Reference semantics: Why?! If two object variables are assigned the same object, the object is NOT copied; instead, the object!s address is copied. " As a result, both variables will point to the same object. " Calling a method on either variable will modify the same object.! Example: Point p1 = new Point(3, 8); Point p2 = p1; p2.setlocation(1, 2); p1 x: 13 y: 28! Objects have reference semantics for several reasons: " efficiency: Objects can be large and bulky. Having to copy them every time they are passed as parameters would slow down the program. " sharing: Since objects hold important state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object. p2 33 34

How not test equality of objects Why so bad?! Objects store references, or addresses.! Comparing two objects with == will test if they have the same address.! This is NOT what you want.! DO NOT DO THIS Point p1 = ; Point p2 = ; if(p1==p2) { BAD Point p1 = new Point(7, 2); Point p2 = new Point(7, 2); p1: x: 7 y: 2 p2: x: 7 y: 2 Is p1==p2 true or false? It s false: they point to different spots in memory. So they store different addresses. But we want it to be true, obviously! How not test equality of objects Operators and object types! DO NOT DO THIS: Point p1 = ; Point p2 = ; if(p1==p2) { BAD

The equals method! All classes in Java have a built-in equals method! For the Point class: p1.equals(p2)! This returns true if p1 and p2 have the same data! It doesn t matter if they reference different locations in memory Object and primitive types: a comparison (so far) Object types Constructed with the new keyword References to memory location that stores their data Can be null (have no data) Can cause NullPointerExceptions Contain state and behavior Use reference semantics Primitive types Values don t need to be constructed Store data directly in memory slot Cannot be null Cannot cause NullPointerExceptions Contain state only Use value semantics Use equals() method Use ==,!=! Likewise, use!p1.equals(p2) instead of p1!=p2