CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is...

33
CMSC 202 Java Classes and Object 2nd Lecture

description

Aug 6, Main Memory The stack grows and shrinks as needed (why?) The used part of the heap (“allocated”) also grows and shrinks. Some of the heap is unused (“free”) StackFree HeapUsed Heap

Transcript of CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is...

Page 1: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

CMSC 202

Java Classes and Object2nd Lecture

Page 2: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 2

Stack and Heap• When your program is running, some memory is

used to store local variables. This memory is known as the stack.

• We can use a table to represent variables stored on the stack

Var Value x 42

y 3.7• The rest of memory is known as the heap and is

used for dynamically allocated “stuff” (recall using malloc( ) in C)

Page 3: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 3

Main MemoryThe stack grows and shrinks as needed (why?)The used part of the heap (“allocated”) also grows and

shrinks. Some of the heap is unused (“free”)

Stack Free Heap Used Heap

Page 4: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 4

Object Creation

Consider this code that creates two stringsString s1, s2;s1 = new String( “abc” );s2 = “abc” ;

Note: Because Strings are very common, using new when creating String objects is optional. Where are these variables and object

located in memory?Why do we care?

Page 5: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 5

Objects in MemoryThe statement String s1, s2; creates two local variables on the stack.The statements

s1 = new String( “abc” );s2 = “abc”;

create objects on the heap. s1 and s2 contain the memory addresses of these objects giving us the picture of memory shown below.

s1 and s2 are called reference variables. Reference variables which do not contain the memory address of any object contain the special value null

s1

s2 abcabc

Stack Heap

Page 6: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 6

Why We Care (1 of 4)Given the previous code

String s1, s2;s1 = new String( “abc” );s2 = “abc”;

and corresponding picture of memory consider the expression s1 == s2

Recall that s1 and s2 contain the addresses of their respective String objects. Since the String objects have different addresses on the heap, s1 == s2 is false. The == operator determines if two reference variables refer to the same object.

So how do we compare Strings for equality?Strings (and other objects) implement a method named equals. To

check if two Strings are the same, use the expression s1.equals( s2 );

.

s1

s2 abcabc

Stack Heap

Page 7: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 7

Why We Care (2 of 4)On the other hand, consider this

code and corresponding picture of memory

String s1 = “abc”;String s2 = s1;

s1

s2 abc

Stack Heap

s1 and s2 are ALIASed

Now s1 and s2 refer to the same String object. This is known as ALIASING, is often unintentional, and can be dangerous.

If your intent is for s2 to be a copy of s1, then the correct code isString s2 = new String( s1 );

Page 8: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 8

Why We Care (3 of 4)Consider this code and the changing picture of memory

String s1 = “abc”; // line 1s1 = “xyz”; // line 2S1 = “Hello”; // line 3

s1 abc

Stack Heap

After line 1

s1 abc

Stack Heap

After line 2

s1 abc

Stack Heap

After line 3

xyz xyz

Hello

Page 9: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 9

Why We Care (4 of 4)• Garbage collectionAs the diagram shows, after line 3

is executed no variable refers to the String objects which contain “abc” or “xyz”.

s1 abc

Stack Heap

After line 3

xyz

Hello

In C/C++, we’d consider this a “memory leak”. In C/C++ it’s the programmer’s responsibility to return dynamically allocated memory back to the free heap. (recall using malloc and free in C?) Not so in Java!

Java has a built-in “garbage collector”. From time to time Java detects objects has been “orphaned” because no reference variable refers to them. The garbage collector automatically returns the memory for those objects to the free heap.

Page 10: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 10

Java expects certain methods to be implemented in virtually all class because some of the Java standard library functions assume they are defined.

equals is one such method. This method compares two objects of the same class to see if they satisfy the intuitive definition of “being equal”. equals returns a Boolean value.

Recall that you cannot use == to determine object equality.

In general, the method definition of equals ispublic boolean equals( ClassName ParameterName)

Page 11: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 11

equals for Date1

Here’s an implementation of equals for our Date1 class. Two Date1 objects are equal if and only if they have identical month, day, and year

public boolean equals( Date1 otherDate){

return month.equals(otherDate.month)&& day == otherDate.day && year == otherDate.year;

}

This is the equals method for theString class

== okay here because day and year are intsUse == with primitive types, NOT with objects

Page 12: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 12

toString

While we’re on the subject, another method that Java assumes we have defined is toString.

• The purpose of the toString method is to return a String value that represents the data in the object public String toString()

Page 13: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 13

toString for Date1

Here’s a possible implementation of the toString method for Date1. You’re free to return any meaningful string such as

“January 23, 1982” or “23 January 1982”

public String toString( ){return month + “ “ + day + “, “ + year;

}

Page 14: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 14

OOP TechniquesWe’ve seen how creating classes allows to

combine the data and operations into a single entity. This technique is known as encapsulation and is a key part of OOP.

Another, even more important technique in OOP is information hiding. This means separating the description of how to use the class from the details of the class implementation.

Information hiding is also known as abstraction. Abstracting something means discarding some of the details.

Page 15: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 15

Information HidingWhy is information hiding (abstraction) a good

thing?Using information hiding means that the

programmer that uses your class does not need to know how the class is implemented, only how to use it. This keeps the information the programmer needs to a minimum.

Just as important, if the users of your class don’t know how it’s implemented, you can change the implementation with no impact on those who use your class.

Page 16: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 16

Date2 ClassIn this new class, the instance variable have been labeled private

public class Date2{

private String month;private int day;

private int year;

public void print( ){

System.out.println(month + “ “ + day + “ “ + year);}

// setDate and monthString included}

Page 17: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 17

Visibility ModifiersIn our Date1 class, the instance variables were labeled as public. As we saw in Date1Demo, there

were no restrictions on how these variables could be used.In Date2, we changed the visibility modifier from public to private. Private instance variables (and

methods) are only accessible within their class. So code like this produces compiler errors.

public class Date2Demo{

public static void main( String[ ] args ){

Date2 myDate = new Date2( );

myDate.month = “July”; // compiler errormyDate.day = 4; // compiler errormyDate.year = 1950; // compiler error

myDate.setDate( 7, 4, 1950); // OK – why?myDate.print( ); // OK – why?

}}

Page 18: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 18

Private Instance VariableIt’s good programming practice to label all instance

variables as private. Doing so means that the class has complete control over how/when/if the instance variables are changed.

But if the instance variables are private, how does the class user access or modify them?

IF the class implementer wants to allow the class user the privilege of accessing or modifying private instance variables, the implementer provides public methods known as accessors and mutators. These methods give the class user indirect access to the instance variables. The degree of access is still controlled by the class implementer.

Page 19: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 19

Accessors & Mutator

An accessor is a method whose purpose is to retrieve the value of a (private) instance variable. It’s conventional to start the name of an accessor method with get.

A mutator is a method that allows you to change the value of an instance variable. It’s conventional to start the name of an mutator with set.

Page 20: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 20

More Accessors and Mutators

Question: Don’t the use of accessors and mutators defeat the purpose of making the instance variable private?

Answer: No.1. The class implementer decides which instance variables will have accessors.2. Mutators can validate the new value of the instance variable and decide whether or not to actually make the requested change.

Page 21: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 21

New Class Model

The use of private instance variables, accessors, and mutators gives us a better class model as shown in the diagram below.

Page 22: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 22

Encapsulation

Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Page 23: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 23

Date2 Accessor & Mutatorpublic class Date2{

private String month;private int day; // 1 - 31private int year;// 4-digit year

// accessors return the value of private datapublic int getDay ( ){ return day; }

// mutators can validate the new valuepublic boolean setYear(int newYear ){if (newYear < 1000 || newYear > 9999){ // this is an invalid year return false;}else{ year = newYear; return true;}// rest of class definition follows

}

Page 24: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 24

Other Methods and CommentsClasses can provide many methods (besides

accessors and mutators) that perform a variety of behaviors. Clear communication with the class user is of paramount importance so that he can use the appropriate method and use class methods properly.

One important way of communicating with the class user is through the use of comments about each method.

Two important types of method comments are known as pre-conditions and post-conditions.

Page 25: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 25

Pre- and Post-Condition

A pre-condition states what is assumed to be true when a method is called.

If any pre-condition is not met, the method cannot correctly perform its function.

A post-condition describes the effect of the method. It states what will after the method executes (assuming all pre-conditions are met).

Page 26: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 26

A simple exampleRecall the print method from Date2 that outputs the month

string, day, and year to the screen. The print method might look something like this

/* PreCondition: all instance variables of the calling object have a meaningful value

PostCondition: The calling object has been written to the screen in the format

<month string> <day>, <year>*/public void print( ){

// code here}

Page 27: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 27

Another common exampleVery often the pre-condition specifies the limits of the parameters and the post-

condition says something about the return value/* Pre-condition:

1 <= month <= 121 <= day <= 31 and appropriate for the month1000 <= year <= 9999Post-Condition:The month, day, and year of the calling object have been set to the parameter values.Return true if the calling object has been changedReturns false otherwise

*/public boolean setDate( int month, int day, int year){

// code here}

Page 28: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 28

What’s in a name?

Not suprisingly, many different classes can all define a method with the same name (e.g. equals, toString). Java can determine which method to call based on the type of the calling object.

A little more suprising, however, is that two or more methods in the same class may have the same name. This is known as method overloading.

Page 29: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 29

Overloaded setDateIn our Date2 class, we introduced the

setDate methodpublic boolean setDate( int month, int day, int year)

But suppose we wanted to change only the day and year? We can define another method named setDate like this

public boolean setDate( int day, int year)

(after all, setDate is a good descriptive name for what this method does)

Page 30: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 30

Date3 Class with overloadedsetData method

public class Date3{

private String month;private int day; // 1 - 31private int year; // 4 digits

public boolean setDate( int newMonth, int newDay, int newYear){

// code here}

public boolean setDate( int newDay, int newYear );{

// code here, doesn’t change month}// print(), monthString( ), setYear( ) follow

}

Page 31: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 31

Date3Demopublic class Date3Demo{

public static void main (String[ ] args){

Date3 myDate = new Date3( );

myDate.setDate( 1, 23, 1982 );myDate.print( );

myDate.setDate( 4, 1999 );myDate.print( );

}}

How does Java know which setDate to call?

Page 32: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 32

Method Signature

In Java (and other OO languages), a method is uniquely identified by its name and its parameter list (parameter types and their order).

public boolean setDate( int newMonth, int newDay, int newYear)public boolean setDate( String newMonth, int newDay, int newYear)public boolean setDate( int newDay, int newYear)public boolean setDate( int newDay, String newMonth)

Page 33: CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, 20072 Stack and Heap When your program is running, some memory is used to store local variables.

Aug 6, 2007 33

Too much of a good thingAutomatic type promotion and overloading can sometimes interact in ways that

confuse the compiler. Consider this simple examplepublic class X{

...public void printAverage ( int a, double b) //version 1...public void printAverage ( double a, int b) //version 2

}And then consider this code snippet

myX = new X( );myX.printAverage( 5, 7 );

The Java compiler can’t decide whether to promote 7 to 7.0 and call the first version of printAverage or to promote 5 to 5.0 and call the second.

The Java compiler is confused and will issue an error stating that the method invocation of myX.printAverage is ambiguous