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

Post on 21-Dec-2015

243 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

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 yieldsreferences

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

namepriceshares

namepriceshares

ibm

sun

declarereferences

Stock ibm;Stock sun;

ibm = new Stock();sun = new Stock();

allocateobjects

5

Assignment

• Assignment of reference types copies only the reference– does not create new object

namepriceshares

ibm

s

Stock ibm = new Stock();Stock s;

s = ibm;now refer tosame 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 isreference topassed object

pass referencetype as parameter name

priceshares 0

s

ibm

8

comparereferences?

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 IBMprice 56.0shares 100

name Sunprice 7.50shares 200

ibm

sun

comparedata?

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 todifferent 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 documentationof Stock class todetermine 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, runtimeexception generated

Stock s;...if (s != null) s.Buy(50);...

test referencebefore 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();

centerradius c

14

Reference field initial value

• Reference fields default to null

Circle c = new Circle();

center nullradius 0

c

center willbe null

15

Contained objects

• Objects for reference fields typically allocated at initialization

allocatecenterPoint

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);

centerradius 3 c

x 1y 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 topassed 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 ofreferences

objects

stocks

namepriceshares

namepriceshares

namepriceshares

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

namepriceshares

namepriceshares

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 longerin use, now eligibleto 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

XX

24

Timing of garbage collection

• Garbage collector execution managed by system– runs as needed

void Allocate(){ int[] a = new int[10000]; ...}

collection of unusedobjects may occurif needed to satisfythis 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 failif 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

top related