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,

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

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:
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Java Syntax Primitive data types Operators Control statements.
Fundamental Programming Structures in Java: Strings.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Objects & Object Oriented Programming Weiss ch. 3.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
OOP Languages: Java vs C++
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Objects, Classes and Syntax Dr. Andrew Wallace PhD BEng(hons) EurIng
1 CIS 2168 Data Structures and Algorithms in JAVA Brief Introduction to JAVA.
Objects.
Peyman Dodangeh Sharif University of Technology Fall 2013.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Controlling Program Flow. Data Types and Variable Declarations Controlling Program Flow.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
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.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Object Oriented Software Development 4. C# data types, objects and references.
Programming Languages and Paradigms Activation Records in Java.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Peyman Dodangeh Sharif University of Technology Spring 2014.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Reference Types CSCI-1302 Lakshmish Ramaswamy. Reference Variables Java supports 8 primitive types All other types are reference types Reference variable.
Object Oriented Programming Lecture 2: BallWorld.
CS314 – Section 5 Recitation 9
Chapter 7 User-Defined Methods.
“Interview coding is not the same skill as coding in real life where you have Stack Overflow, reference materials, and an editor. ”
Java Review: Reference Types
Building Java Programs
Building Java Programs
Java Programming Language
Java Basics Data Types in Java.
In this class, we will cover:
Building Java Programs
Building Java Programs
Classes and Objects Object Creation
Presentation transcript:

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, Point, arrayOfInteger, arrayOfString, etc. –“object” and “instance” are synonyms Each object has named contents –called instance variables or member variables or fields –Binding: Each name assigned one slot in the object’s memory region, as an offset from the start of the object Each object has associated methods –called instance methods or member methods –these are shared between all instances of a type

Example: A Point Instance int x Point 5 int y -3 int color 0xFF0000 int x Point 10 int y 2 int color 0x00FF00 type shown at top three instance variables heap another instance of type Point: this time at coordinates (10, 2) with color 0x00FF00 (green) shaded area not actually stored in memory

y Objects What can we do with an object? –e.g., want to change the coordinates of “that second instance of Point that has color green”. –Need to name objects, so we can refer to them.

References Memory addresses –Each slot in memory has an address (number) –Physically and logically: each location in each chip of RAM is numbered consecutively, starting at 0 and counting upwards We can refer to an object by its address in the heap –In Java, you (the user) rarely get to see the actual address xFF0000 Point x00FF00 Point heap … …

Reference Variables A reference variable stores the address of an object, or null –Used to refer to a particular object on the heap, or to nothing –Think: a “pointer” to the object –Usually called just reference for short xFF0000 Point x00FF00 Point heap … … static double drawLine( String label, // ref. to a String Point p1, // ref. to a Point Point p2, // ref. to a Point int color) { Point p3 = null; … } stack just after call to drawLine(…) 5 null p3 color p2 p1 label

What can we do with a reference? 1.Assignment p1 = p2 2.Equality testing p1 == p2 p1 != p2 3.Access the members of the object that it refers to (“points at”): p1.x 4.Type conversions (later) 5.instanceof operator (later) these operate on the reference variables themselves, not the objects referred to these operate on the objects that are pointed at

Constructing New Objects new Point() –allocates space for a new object/instance of type Point on the heap –initializes its fields (to all zeros, in this case) –returns a reference to it Often specify parameters during creation: –new Point(5, -3)  initialize to x=5, y=-3, default color –new Point(10 2, RED)  initialize to x=10, y=2, color=RED

A Very Detailed Example public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+" to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); }

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Main is called –reference to an array of Strings is on top of stack –stack frame allocated for other variables heap … … 6022 d p2 p1 y2 x2 y1 x1 args stack

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Uses a static method in class Integer to convert String to integer heap d p2 p1 y2 x2 y1 x1 args stack … …

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Remaining args parsed heap d p2 p1 y2 x2 y1 x1 args stack … …

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Creates a new Point object on heap Initializes it to have coordinates x1, y1, default color Assigns p1 to refer to the new object x0 Point heap … … d p2 p1 y2 x2 y1 x1 args 3010 stack

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Creates a second Point object on heap Initializes it to have coordinates x2, y2, default color Assigns p2 to refer to the new object x0 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } calling distance( ) Pushes parameters p1 and p2 These become a and b x0 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack baba

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Accesses objects pointed to by a and b reads the field x from each x0 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack dy dx b a

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Accesses field y from objects x0 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack dy dx b a

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Computes result, and returns it x0 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack 7.071

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Assigns return value to d x0 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack 7.071

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Compares d to 10 Then access object pointed to by p1 and sets color to RED xFF0000 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack

public static void main(String args[ ]) { int x1 = Integer.parseInt(args[0]); int y1 = Integer.parseInt(args[1]); int x2 = Integer.parseInt(args[2]); int y2 = Integer.parseInt(args[3]); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); double d = distance(p1, p2); if (d < 10) p1.color = RED; else p1.color = GREEN; System.out.println("Distance from "+p1+ " to "+p2+" is "+d); } static double distance(Point a, Point b) { int dx = a.x - b.x; int dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } Prints results xFF0000 Point x0 Point heap … … d p2 p1 y2 x2 y1 x1 args stack

Lessons In Java, almost everything is an object: –e.g., String, array of whatever, File, Point –but not primitive types (int, boolean, char, …) Objects have contents: –e.g., Point has x, y, and color Only way to access object contents is through a reference –Can have multiple references to same object –No direct way to figure out the actual address from within a Java program; no way to turn an address (if you had one) back in to a reference.

y References as Parameters Method parameters are a copy of the reference, not the object –Not always intuitive! Consider: –(But the alternative is even more confusing) static void swap(Point p1, Point p2) { Point tmp = p2; p2 = p1; p1 = tmp; } static void destroy(Point p1) { p1.color = 0x0; p1 = null; }

Assignment Same as parameter passing (or rather, vice-versa) Assigns copy of the reference, does not make a copy of the object –Not always intuitive! Consider: –Called aliasing: often confusing! –There is a way to make a copy of an object; rarely used Button noButton = new Button("No"); Button yesButton = new Button(); yesButton = noButton; yesButton.setLabel("Yes"); panel.add(noButton); panel.add(yesButton);

Comparing References Compares the references for equality, not the objects –Not always intuitive! Consider: –Same goes for ‘!=‘ –If you want to compare objects for equality, instead do: Point p1 = new Point(5, 3); Point p2 = new Point(5, 3); if (p1 == p2) System.out.println(“same reference"); if (p1.equals(p2)) System.out.println(“identical objects");

Live and Dead Objects Question: What happens to second Button instance? –Lost forever; call it dead Live objects (a recursive definition) –Anything referred to by another live object Dead objects –the rest –Eventually reclaimed, or garbage collected, by the system Button noButton = new Button("No"); Button yesButton = new Button(); yesButton = noButton;

Method Dispatching Objects have instance methods as well as fields Method dispatching: process of finding the right method to call –Dynamic: looks at object, searches for method with correct name and parameter types. int x Point 5 int y -3 int color 0xFF0000 double angle() int quadrant() p1 System.out.println(“angle is “+p1.angle());

String Like any object, but: –has a special way of creating new ones: “…” “abc” creates a new String, returns reference to it has a special operator for concatenation: + Immutable –All of it’s fields are declared private, so are inaccessible –None of its methods ever change the object –No one can create additional methods for String –Thought exercise: why is this important?

String Concatenation If either lhs or rhs is a (reference to a) String, then ‘+’ means string concatenation; also use “+=“ String concatenation creates a new string object and returns a reference to it If one side not a String, it is converted: –e.g., “abc” + 5  “abc5” 1 + (2 + “3”)  “123” String s = “good”; s = “not” + s; s += “at all”; “good” “not” “not good” “not good at all” s note: s is reassigned!

String Comparison Operators “==“ and “!=“ compare references –Rarely useful for strings –Usually want to compare contents –So use equals() instead String s1 = “Hello”; if (s1 == “Hello”) System.out.println(“oops”); if (s1.equals(“Hello”) System.out.println(“better”); if (“Hello”.equals(s1)) System.out.println(“odd, but okay”);

Other String Methods Other than equals(), there are many –Look in Java API (on web) Inspecting a string: –“Hello”.length()  returns int 5 –“Hello”.charAt(1)  returns char ‘e’ –“Hello”.indexOf(‘o’)  returns int 4 –“Hello”.endsWith(“lo”)  returns boolean true Modifying a string (hey, aren’t they immutable!): –“cs211”.toUpperCase()  returns String “CS211” –“cs211”.replace(‘1’, ‘0’)  returns String “cs200” –“ cs211 “.trim()  returns String “cs211”

Arrays Read Weiss sec. 2.4 Arrays are objects int [ ] a = new int[5]; a[0] = 123; a[4] = a.length; Arrays can hold references as well as primitives String [ ] staff = new String[5]; // initially, all null staff[0] = “Kevin”; // new object, save reference in array String [ ] people = staff; // alias to same array! people[1] = “Eli”; // new object, save reference in array