Reference Types. 2 Objectives Introduce reference types –class –array Discuss details of use –declaration –allocation –assignment –null –parameter –aggregation.

Slides:



Advertisements
Similar presentations
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Advertisements

Language Fundamentals in brief C# - Introduction.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Garbage Collection Introduction What is garbage and how can we deal with it? Garbage collection schemes Reference Counting Mark and Sweep Stop and Copy.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
Garbage Collection What is garbage and how can we deal with it?
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
CSC321: Programming Languages 11-1 Programming Languages Tucker and Noonan Chapter 11: Memory Management 11.1 The Heap 11.2 Implementation of Dynamic Arrays.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
Memory Management. History Run-time management of dynamic memory is a necessary activity for modern programming languages Lisp of the 1960’s was one of.
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Class. 2 Objectives Discuss class basics –fields –methods –access levels Present object creation –new operator.
Run-Time Storage Organization
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Reference Counters Associate a counter with each heap item Whenever a heap item is created, such as by a new or malloc instruction, initialize the counter.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
Ch 4. Memory Management Timothy Budd Oregon State University.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
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.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CSC Programming I Lecture 8 September 9, 2002.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Object-Oriented Programming in C++
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Dale Roberts Object Oriented Programming using Java - Final and Static Keywords Dale Roberts, Lecturer Computer Science, IUPUI
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Finalizers, this reference and static Sangeetha Parthasarathy 06/13/2001.
G ARBAGE C OLLECTION CSCE-531 Ankur Jain Neeraj Agrawal 1.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Objects and Variables Local variables – Confined to single context: allocated on stack – Primitive types such as int or object references – Must be initialized.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
Eliminating External Fragmentation in a Non-Moving Garbage Collector for Java Author: Fridtjof Siebert, CASES 2000 Michael Sallas Object-Oriented Languages.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Core Java Garbage Collection LEVEL – PRACTITIONER.
Module 9: Memory and Resource Management
Java Primer 1: Types, Classes and Operators
Unit-2 Objects and Classes
Object Oriented Programming in java
Created By: Asst. Prof. Ashish Shah, J.M.Patel College, Goregoan West
Dynamic Memory.
Presentation transcript:

Reference Types

2 Objectives Introduce reference types –class –array Discuss details of use –declaration –allocation –assignment –null –parameter –aggregation Introduce garbage collection

3 Reference Variable declaration of class type gives reference –handle only –no object created declaration yields references Stock ibm; Stock sun; ibm sun class Stock {... } class type references, not objects

4 Instance Instance of class types is reference/object pair –object created using new –accessed through reference name price shares name price shares ibm sun declare references Stock ibm; Stock sun; ibm = new Stock(); sun = new Stock(); allocate objects

5 Assignment Assignment of reference types copies only the reference –does not create new object name price shares ibm s Stock ibm = new Stock(); Stock s; s = ibm; now refer to same object

6 Reassignment Reference may be reassigned –can refer to different objects at different times –not required to stay bound to same object Stock ibm = new Stock(); Stock sun = new Stock(); Stock s; s = ibm;... s = sun;... s refers to ibm s refers to sun

7 Parameters Parameters of reference type pass only reference –do not copy object Typical to pass reference by value –but can pass ref or out if needed void Liquidate(Stock s) { s.Sell(s.shares); } Stock ibm = new Stock();... Liquidate(ibm); parameter is reference to passed object pass reference type as parameter name price shares 0 s ibm

8 compare references? Comparison Two possible meanings for reference comparison –identity: do the two references refer to the same object? –equality: do the objects contain equal data? name IBM price 56.0 shares 100 name Sun price 7.50 shares 200 ibm sun compare data?

9 Identity test Use library method to guarantee identity test with references –static method Object.ReferenceEquals Stock ibm = new Stock(); Stock sun = new Stock(); if (Object.ReferenceEquals(ibm, sun))... false, refer to different objects

10 operator == Operator == may perform either identity or equality test –default behavior is identity test –type can customize behavior by overloading operator Stock ibm = new Stock(); Stock sun = new Stock(); if (ibm == sun)... refer to documentation of Stock class to determine behavior

11 Keyword null Assign null to indicate reference does not refer to object –invalidates reference –does not destroy object Stock ibm = new Stock();... ibm = null;... invalidate

12 Using null reference Error to use null reference –can catch and handle NullReferenceException at runtime –can test reference before use and avoid exception Stock s = null; s.Buy(50);... error: s is null, runtime exception generated Stock s;... if (s != null) s.Buy(50);... test reference before use

13 Reference field Common for class to contain reference as field –reference only –not embedded object class Point { int x; int y;... } reference class Circle { Point center; int radius;... } Circle c = new Circle(); center radius c

14 Reference field initial value Reference fields default to null Circle c = new Circle(); center null radius 0 c center will be null

15 Contained objects Objects for reference fields typically allocated at initialization allocate center Point class Circle { public Circle(int x, int y, int radius) { this.center = new Point(x, y); this.radius = radius; }... } Circle c = new Circle(1, 2, 3); center radius 3 c x 1 y 2

16 Array Array declaration gives reference –does not create array object references int [] a; bool[] b; a b

17 Array creation Arrays created using new operator references int [] a; bool[] b; a = new int [5]; b = new bool[3]; create arrays a b

18 Array assignment Array assignment copies only the reference int[] a = new int[5]; int[] b; b = a;... refer to same array a b

19 Array parameters Array parameter passes reference –does not copy array Typical to pass array reference by value –but can pass ref or out if needed int Total(int[] a) { int total = 0; foreach (int i in a) total += i; return total; } int[] data = new int[5];... int t = Total(data); reference to passed array pass array a data

20 Array of class reference Array of class type is array of references –elements default to null –must allocate objects with new and store reference in array Stock[] stocks = new Stock[3]; stocks[0] = new Stock(); stocks[1] = new Stock(); stocks[2] = new Stock(); array of references objects stocks name price shares name price shares name price shares

21 Managed heap Memory for reference types obtained from managed heap –area of memory dedicated for use by the application –allocation optimized to incur only small runtime overhead heap name price shares name price shares ibm sun Stock ibm = new Stock(); Stock sun = new Stock(); int [] a = new int [10]; bool[] b = new bool[5]; a b

22 Garbage collection Memory of unused objects automatically reclaimed –not explicitly released by programmer –called garbage collection void Method() { int[] a = new int[5]; Stock s = new Stock(); } objects no longer in use, now eligible to be reclaimed

23 Garbage collection algorithm Garbage collector finds unreferenced objects –begins at root references such as live local variables –all objects found from some root are still in use –objects not reachable from a root can be collected heap a b references X X X

24 Timing of garbage collection Garbage collector execution managed by system –runs as needed void Allocate() { int[] a = new int[10000];... } collection of unused objects may occur if needed to satisfy this request

25 Control of garbage collection GC class provided to give programmer control if needed –Collect method runs garbage collector Should rarely control garbage collection explicitly –already highly optimized –collection is expensive, waste of time if done unnecessarily public class GC { public static void Collect() {... }... } force collection

26 Allocation failure Heap may eventually run out of available memory –attempted allocation will fail –OutOfMemoryException will be generated –application can catch and handle exception if desired int[] a = new int[10000]; allocation may fail if out of memory

27 Summary Reference/object pair used for class instance and array Reference semantics apply in –assignment –comparison –parameter passing Garbage collection automatically reclaims unused memory –relieves programmer of responsibility