Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 CMSC 202 Java Classes and Object 2nd Lecture

2 Aug 6, 20072 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)

3 Aug 6, 20073 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

4 Aug 6, 20074 Object Creation Consider this code that creates two strings String 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?

5 Aug 6, 20075 Objects in Memory The 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 s2abc Stack Heap

6 Aug 6, 20076 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 s2abc Stack Heap

7 Aug 6, 20077 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 s2abc 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 is String s2 = new String( s1 );

8 Aug 6, 20078 Why We Care (3 of 4) Consider this code and the changing picture of memory String s1 = “abc”; // line 1 s1 = “xyz”;// line 2 S1 = “Hello”; // line 3 s1abc StackHeap After line 1 s1abc StackHeap After line 2 s1abc StackHeap After line 3 xyz Hello

9 Aug 6, 20079 Why We Care (4 of 4) Garbage collection As the diagram shows, after line 3 is executed no variable refers to the String objects which contain “abc” or “xyz”. s1abc StackHeap 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.

10 Aug 6, 200710 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 is public boolean equals( ClassName ParameterName)

11 Aug 6, 200711 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 the String class == okay here because day and year are ints Use == with primitive types, NOT with objects

12 Aug 6, 200712 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()

13 Aug 6, 200713 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; }

14 Aug 6, 200714 OOP Techniques We’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.

15 Aug 6, 200715 Information Hiding Why 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.

16 Aug 6, 200716 Date2 Class In 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 }

17 Aug 6, 200717 Visibility Modifiers In 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 error myDate.day = 4;// compiler error myDate.year = 1950;// compiler error myDate.setDate( 7, 4, 1950);// OK – why? myDate.print( );// OK – why? }

18 Aug 6, 200718 Private Instance Variable It’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.

19 Aug 6, 200719 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.

20 Aug 6, 200720 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.

21 Aug 6, 200721 New Class Model The use of private instance variables, accessors, and mutators gives us a better class model as shown in the diagram below.

22 Aug 6, 200722 Encapsulation Copyright © 2008 Pearson Addison-Wesley. All rights reserved

23 Aug 6, 200723 Date2 Accessor & Mutator public class Date2 { private String month; private int day;// 1 - 31 private int year;// 4-digit year // accessors return the value of private data public int getDay ( ) { return day; } // mutators can validate the new value public boolean setYear(int newYear ) { if (newYear 9999) { // this is an invalid year return false; } else { year = newYear; return true; } // rest of class definition follows }

24 Aug 6, 200724 Other Methods and Comments Classes 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.

25 Aug 6, 200725 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).

26 Aug 6, 200726 A simple example Recall 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, */ public void print( ) { // code here }

27 Aug 6, 200727 Another common example Very often the pre-condition specifies the limits of the parameters and the post- condition says something about the return value /* Pre-condition: 1 <= month <= 12 1 <= day <= 31 and appropriate for the month 1000 <= year <= 9999 Post-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 changed Returns false otherwise */ public boolean setDate( int month, int day, int year) { // code here }

28 Aug 6, 200728 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.

29 Aug 6, 200729 Overloaded setDate In our Date2 class, we introduced the setDate method public 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)

30 Aug 6, 200730 Date3 Class with overloaded setData method public class Date3 { private String month; private int day;// 1 - 31 private 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 }

31 Aug 6, 200731 Date3Demo public 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?

32 Aug 6, 200732 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)

33 Aug 6, 200733 Too much of a good thing Automatic type promotion and overloading can sometimes interact in ways that confuse the compiler. Consider this simple example public 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


Download ppt "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."

Similar presentations


Ads by Google