1 2 Classes and Objects A Deeper Look
1 2 Classes and Objects: A Deeper Look 1992 -2007 Pearson Education, Inc. All rights reserved.
2 class Time overview • Class Time has – 5 constructors – 4 get and set methods – 2 String methods 1992 -2007 Pearson Education, Inc. All rights reserved.
3 Constructors of Time • Class Time has • 5 constructors Time() // no argument constructor Time(int h) // specifies hour, minute and second have values 0 Time(int h, int m) // specifies hour and munite, second has value 0 Time(int h, int m, int s) // specifies hour, munite and second Time(Time t) // takes a Time 2 object and creates a copy of the object extracting its hour, minute and second values 1992 -2007 Pearson Education, Inc. All rights reserved.
4 get and set methods of Time • Class Time has • 4 get and 4 set methods – – set. Time(int h, int m, int s) set. Hour(int h) set. Munite(int m) set. Second(int s) • 4 get methods – – int get. Hour() int get. Minute() int get. Second() Time get. Time() 1992 -2007 Pearson Education, Inc. All rights reserved.
5 Display methods of Time • 2 String methods – to. String() – to. Universal. String() 1992 -2007 Pearson Education, Inc. All rights reserved.
6 Time Class // Time. java // Time class declaration constructors. public class Time { private int hour; // private int minute; // private int second; // with overloaded 0 - 23 0 - 59 // Time no-argument constructor: initializes each instance variable // to zero; ensures that Time 2 objects start in a consistent state public Time() { this( 0, 0, 0 ); // invoke Time constructor with three arguments } // end Time no-argument constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
7 Time Class (cont. ) // Time constructor: hour supplied, minute and second defaulted to 0 public Time( int h ) { this( h, 0, 0 ); // invoke Time 2 constructor with three arguments } // end Time one-argument constructor // Time constructor: hour and minute supplied, second defaulted to 0 public Time( int h, int m ) { this( h, m, 0 ); // invoke Time 2 constructor with three arguments } // end Time two-argument constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
8 Time Class (cont. ) // Time constructor: hour, minute and second supplied public Time( int h, int m, int s ) set. Time( h, m, s ); // invoke set. Time to validate time } // end Time three-argument constructor // Time constructor: another Time object supplied public Time( Time time ) { // invoke Time three-argument constructor this( time. get. Hour(), time. get. Minute(), time. get. Second() ); } // end Time constructor with a Time 2 object argument 1992 -2007 Pearson Education, Inc. All rights reserved.
9 Time Class (cont. ) // Set Methods // set a new time value using universal time; ensure that // the data remains consistent by setting invalid values to zero public void set. Time( int h, int m, int s ) { set. Hour( h ); // set the hour set. Minute( m ); // set the minute set. Second( s ); // set the second } // end method set. Time 1992 -2007 Pearson Education, Inc. All rights reserved.
10 Time Class (cont. ) // validate and set hour public void set. Hour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // end method set. Hour // validate and set minute public void set. Minute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // end method set. Minute // validate and set second public void set. Second( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // end method set. Second 1992 -2007 Pearson Education, Inc. All rights reserved.
11 Time Class (cont. ) // Get Methods // get hour value public int get. Hour() { return hour; } // end method get. Hour // get minute value public int get. Minute() { return minute; } // end method get. Minute // get second value public int get. Second() { return second; } // end method get. Second 1992 -2007 Pearson Education, Inc. All rights reserved.
12 Time Class (cont. ) // convert to String in universal-time format (HH: MM: SS) public String to. Universal. String() { return String. format( "%02 d: %02 d", hour, minute, second ); } // end method to. Universal. String 1992 -2007 Pearson Education, Inc. All rights reserved.
13 Time Class (cont. ) // convert to String in standard-time format // (H: MM: SS AM or PM) public String to. String() { return String. format( "%d: %02 d %s", hour==0 || hour==12 ? 12 : hour % 12, minute, second, hour<12 ? "AM": "PM" ); } // end method to. String } // end class Time 1992 -2007 Pearson Education, Inc. All rights reserved.
14 use fo this in constuctors • this(arguments of anbother constructor) • first statent in a constructor • syntax error when this is used in a constructor’s body to call another constructor of the same class if that call is not the first statement in the constructor. • syntax error when a method attempts to invoke a constructor directly via this. 1992 -2007 Pearson Education, Inc. All rights reserved.
15 set. Time method public void set. Time(int h, int m, int s) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second } // end method set. Time hour: between 0 and 23 minute: between 0 and 59 second: betwee 0 and. 59 This is not a constructor shoud be invoked over a Time objcet after the object’s creation with new via default constrfuctor. 1992 -2007 Pearson Education, Inc. All rights reserved.
16 ? the ternary operator in Java hour = (( h >= 0 && h < 24 ) ? h : 0 ); ? is the ternary operator in java General form: condition ? expression 1 : expresion 2; condition is a logical expresion if the condition is true exprsion 1 is evaluated else expresion 2 is evaluated Equivalent to a clasical if statement as follows: if(condition) variable = expresion 1; else variable = expresion 2; 1992 -2007 Pearson Education, Inc. All rights reserved.
17 ? the ternary operator in Java (cont. ) hour = ( h >= 0 && h < 24 ) ? h : 0; The right side of assignment reuturns either current value of h or 0 Depending on the truth value of h >= 0 && h < 24 İf h is between 0. . 23 the expresion is true Equivalent to İf(( h >= 0 && h < 24 )) hour = h; else hour = 0: 1992 -2007 Pearson Education, Inc. All rights reserved.
18 ? the ternary operator in Java (cont. ) the same expresion can be written in a different form using De. Morgon’s rules: !(p and q) = !p or !q hour = ( h < 0 || h > 23 ) ? 0 : h; Equivalent to İf(( h < 0 || h > 23 )) hour = 0; else hour = h: 1992 -2007 Pearson Education, Inc. All rights reserved.
19 String method format • String method format – Similar to printf except it returns a formatted string instead of displaying it in a command window – A static method of the String class – invoked over class name String – need not create any string object 1992 -2007 Pearson Education, Inc. All rights reserved.
20 method to. Universal. String public String to. Universal. String() { return String. format( "%02 d: %02 d", hour, minute, second ); } // end method to. Universal. String "%02 d: %02 d“ determines The format %02 d an integer two digints 0 means if first is blank fill with 0 s 1992 -2007 Pearson Education, Inc. All rights reserved.
21 method to. Universal. String (cont. ) This method can be written like that public String to. Universal. String() { String s = String. format( "%02 d: %02 d", hour, minute, second ); return s; } String. formant() returns a string which is assigned to String variable s e. g. : if hour 2, munite 15 second 5 S becomes “ 02: 15: 05” 1992 -2007 Pearson Education, Inc. All rights reserved.
22 method to. Striing public String to. String() { return String. format( "%d: %02 d %s”, (( hour == 0 || hour == 12 ) ? 12 : hour % 12 minute, second, ( hour < 12 ? "AM" : "PM" ) ); } "%d: %02 d %s” // what to format three int one string ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) Second and third are just munite and second Forth is a stirng either AM or PM 1992 -2007 Pearson Education, Inc. All rights reserved.
23 mappings hour 0 1 11 12 13 12 1 11 PM 23 mpapped to 12 1 11 AM 1992 -2007 Pearson Education, Inc. All rights reserved.
24 First argument ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) İf hour is 0 or 12 12 is returned else hour mod 12 is returned Examples: Time: 00: 15: 20 -> 12: 15: 20 AM Time: 05: 15: 20 -> 5: 15: 20 AM as 5 % 12 = 5 Time: 12: 15: 20 -> 12: 15: 20 PM Time: 21: 15: 20 -> 9: 15: 20 PM as 21 % 12 = 9 1992 -2007 Pearson Education, Inc. All rights reserved.
25 to. String Can be used without refering the method name in a string expression the when the obcet name appears immediately called to produce a string representation of the object 1992 -2007 Pearson Education, Inc. All rights reserved.
26 Test class for using Time Create Time objects with noargument constructor Set hour munite second Display in universal and standard formats Illustrate the use of special nature of to. Sting method when displaying an object 1992 -2007 Pearson Education, Inc. All rights reserved.
27 class Test. Time public class Time 1 Test { public static void main( String args[] ) { // create and initialize a Time 1 object Time time = new Time(); // invokes Time 1 constructor // output string representations of the time System. out. print( "The initial universal time is: " ); System. out. println( time. to. Universal. String() ); System. out. print( "The initial standard time is: " ); System. out. println( time. to. String() ); // explicitly calling to. String System. out. println(); // output a blank line 1992 -2007 Pearson Education, Inc. All rights reserved.
28 class Test. Time (cont. ) // change time and output updated time. set. Time( 13, 27, 6 ); System. out. print( "Universal time after set. Time is: " ); System. out. println( time. to. Universal. String() ); System. out. print( "Standard time after set. Time is: " ); System. out. println( time ); // implictitly to. String is colled System. out. println(); // output a blank line 1992 -2007 Pearson Education, Inc. All rights reserved.
29 class Test. Time (cont. ) // set time with invalid values; output updated time. set. Time( 99, 99 ); System. out. println( "After attempting invalid settings: " ); System. out. print( "Universal time: " ); System. out. println( time. to. Universal. String() ); System. out. print( "Standard time: " ); System. out. println( time. to. String() ); // to. String is called explcitly } // end main } // end class Time 1 Test 1992 -2007 Pearson Education, Inc. All rights reserved.
30 The output The initial universal time is: 00: 00 The initial standard time is: 12: 00 AM Universal time after set. Time is: 13: 27: 06 Standard time after set. Time is: 1: 27: 06 PM After attempting invalid settings: Universal time: 00: 00 Standard time: 12: 00 AM 1992 -2007 Pearson Education, Inc. All rights reserved.
31 Test class for using Time Create Time objects with different constructors Set hour munite second Display in universal and standard formats 1992 -2007 Pearson Education, Inc. All rights reserved.
32 public class Time. Test { public static void main( String args[] ) { Time t 1 = new Time(); // 00: 00 Time t 2 = new Time( 2 ); // 02: 00 Time t 3 = new Time( 21, 34 ); // 21: 34: 00 Time t 4 = new Time( 12, 25, 42 ); // 12: 25: 42 Time t 5 = new Time( 27, 74, 99 ); // 00: 00 Time t 6 = new Time( t 4 ); // 12: 25: 42 1992 -2007 Pearson Education, Inc. All rights reserved.
33 ); System. out. println( "t 1: all arguments defaulted" System. out. printf( " %sn", t 1. to. Universal. String() ); System. out. printf( " %sn", t 1. to. String() ); System. out. println( "t 2: hour specified; minute and second defaulted" System. out. printf( " t 2. to. Universal. String() ); System. out. printf( " %sn", t 2. to. String() ); 1992 -2007 Pearson Education, Inc. All rights reserved.
34 ); System. out. println( "t 3: hour and minute specified; second defaulted" System. out. printf( " t 3. to. Universal. String() ); System. out. printf( " %sn", t 3. to. String() ); System. out. println( "t 4: hour, minute and second specified" ); System. out. printf( " %sn", t 4. to. Universal. String() ); System. out. printf( " %sn", t 4. to. String() ); 1992 -2007 Pearson Education, Inc. All rights reserved.
35 System. out. println( "t 5: all invalid values specified" ); System. out. printf( " %sn", t 5. to. Universal. String() ); System. out. printf( " %sn", t 5. to. String() ); System. out. println( "t 6: Time object t 4 specified" System. out. printf( " t 6. to. Universal. String() ); System. out. printf( " } // end main } // end class Time 2 Test %sn", t 6. to. String() ); 1992 -2007 Pearson Education, Inc. All rights reserved.
36 output t 1: all arguments defaulted 00: 00 12: 00 AM t 2: hour specified; minute and second defaulted 02: 00: 00 AM t 3: hour and minute specified; second defaulted 21: 34: 00 9: 34: 00 PM t 4: hour, minute and second specified 12: 25: 42 PM t 5: all invalid values specified 00: 00 12: 00 AM t 6: Time 2 object t 4 specified 12: 25: 42 PM 1992 -2007 Pearson Education, Inc. All rights reserved.
37 2. 2 Composition • Composition – A class can have references to objects of other classes as members – Sometimes referred to as a has-a relationship 1992 -2007 Pearson Education, Inc. All rights reserved.
38 • Employee class – atributes • name, lastname : String • hire and birth dates : a Date object • Date class • day, month, year • A constructor and • check. Month and check. Day methods – Check if month is 1. . 12 – Day is 1. . Proper for a month considering leap years – to. String method 1992 -2007 Pearson Education, Inc. All rights reserved.
39 class Empleyee. Test 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Fig. 8. 9: Employee. Test. java // Composition demonstration. public class Employee. Test { public static void main( String args[] ) { Date birth = new Date( 7, 24, 1949 ); Date hire = new Date( 3, 12, 1988 ); Employee employee = new Employee( "Bob", "Blue", birth, hire ); System. out. println( employee ); } // end main } // end class Employee. Test 1992 -2007 Pearson Education, Inc. All rights reserved.
40 output Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949 1992 -2007 Pearson Education, Inc. All rights reserved.
41 class Date 4 public class Date 5 { 6 private int month; // 1 -12 7 private int day; // 1 -31 based on month 8 private int year; // any year 9 10 // constructor: call check. Month to confirm proper value for month; 11 // call check. Day to confirm proper value for day 12 public Date( int the. Month, int the. Day, int the. Year ) 13 { 14 month = check. Month( the. Month ); // validate month 15 year = the. Year; // could validate year 16 day = check. Day( the. Day ); // validate day 17 18 System. out. printf( 19 "Date object constructor for date %sn", this ); 20 } // end Date constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
42 class Date (cont. ) 22 23 24 25 26 27 28 29 30 31 32 33 // utility method to confirm proper month value private int check. Month( int test. Month ) { if ( test. Month > 0 && test. Month <= 12 ) // validate month return test. Month; else // month is invalid { System. out. printf( "Invalid month (%d) set to 1. ", test. Month ); return 1; // maintain object in consistent state } // end else } // end method check. Month 1992 -2007 Pearson Education, Inc. All rights reserved.
43 class Date (cont. ) 35 // utility method to confirm proper day value based on month and year 36 private int check. Day( int test. Day ) 37 { 38 int days. Per. Month[] = 39 { 0, 31, 28, 31, 30, 31 }; 40 41 42 43 44 45 46 48 49 50 ); 51 52 // check if day in range for month if ( test. Day > 0 && test. Day <= days. Per. Month[ month ] ) return test. Day; // check for leap year if ( month == 2 && test. Day == 29 && isleap(year)) return test. Day; System. out. printf( "Invalid day (%d) set to 1. ", test. Day return 1; // maintain object in consistent state } // end method check. Day 1992 -2007 Pearson Education, Inc. All rights reserved.
44 class Date (cont. ) 54 // return a String of the form month/day/year 55 56 57 58 public String to. String() { return String. format( "%d/%d/%d", month, day, year ); } // end method to. String 1992 -2007 Pearson Education, Inc. All rights reserved.
45 class Date (cont. ) 59 // return true of false 60 private boolean is. Leap(int test. Year) 61 { 62 return ( test. Year % 400 == 0 ) || ( test. Year % 4 == 0 && test. Year % 100 != 0 ) ; 63 } // end method to. String 64 } // end class Date 1992 -2007 Pearson Education, Inc. All rights reserved.
46 class Employee 4 public class Employee 5 { 6 private String first. Name; 7 private String last. Name; 8 private Date birth. Date; 9 private Date hire. Date; 10 11 // constructor to initialize name, birth date and hire date 12 public Employee( String first, String last, Date date. Of. Birth, Date date. Of. Hire ) 14 15 16 17 18 19 { first. Name = first; last. Name = last; birth. Date = date. Of. Birth; hire. Date = date. Of. Hire; } // end Employee constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
47 class Employee (cont. ) 21 22 23 24 25 26 27 // convert Employee to String format public String to. String() { return String. format( "%s, %s Hired: %s Birthday: %s", last. Name, first. Name, hire. Date, birth. Date ); } // end method to. String } // end class Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
48 Leap year problem • A year is a leap year if • it is divided by 4 • it is not a century year not divided by 100 • but it is divided by 400 • Develop a method – taking an int as a parameter representing a year – returning true or false – depedning on the year is a leap year or not 1992 -2007 Pearson Education, Inc. All rights reserved.
49 Exercise • Leap year problem • Given a year determine whether it is a leap year or not • i. A year is a leap year if it is evenly divided by 4 – 2016, 2000, 1900 are but – 2005, 2001 not • ii. in addition it not evenly divided by 100 – 2016 is but – 2000 is not as 2000 mode 100 = 0 • iii. in addition evenly divided by 400 – 2000 is as 2000 mde 400 = 0 but – 1900 is not, as 1900 mode 100 =0 by B and 1900 mode 400 =300 not zero 1992 -2007 Pearson Education, Inc. All rights reserved.
50 1900 2000 C year mode 400=0 B year mode 100 = 0 2004 A. Year mode 4 = 0 1992 -2007 Pearson Education, Inc. All rights reserved.
51 • • • i: year in set A i can be codes as if (year % 4 == 0) ii: year in set A but not in B ii can be coded as if (year % 4 == 0 && year % 100 !=0 ) Solve iii yourself Solve the same problem both i ii and iii without using logical oppertators (and, or, not) 1992 -2007 Pearson Education, Inc. All rights reserved.
52 As sets • year b 1 year % 4 ==0 b 2 b 3 year % 100 !=0 year %400==0 -----------------------------2009 false true false 2008 true false true 2000 true false true 1900 true false year%4==0 &&(year%100!=0 || year%400==0) 1992 -2007 Pearson Education, Inc. All rights reserved.
53 Pseudo code and Java code • Set C or (Set A but not in Set B) • In Java it is coded as – year % 400==0 || (year % 4 == 0 && year % 100 !=0) – in set C or ( in set A and not in Set B ) 1992 -2007 Pearson Education, Inc. All rights reserved.
54 Another solution • Solve the same problem without using logical operators (and , or) – Using only if – else • Pseudo code if year mode 400 = 0 then leap year else if year mode 100 = 0 then in set C if year mode 100 = 0 not a leap year else if year mode 4 = 0 then leap year else not a leap year 1992 -2007 Pearson Education, Inc. All rights reserved.
55 2. 3 static Class Members • static fields – Also known as class variables – Represents class-wide information – Used when: • all objects of the class should share the same copy of this instance variable or • this instance variable should be accessible even when no objects of the class exist – Can be accessed with the class name or an object name and a dot (. ) – Must be initialized in their declarations, or else the compiler will initialize it with a default value (0 for ints) 1992 -2007 Pearson Education, Inc. All rights reserved.
56 Software Engineering Observation 8. 11 Use a static variable when all objects of a class must use the same copy of the variable. 1992 -2007 Pearson Education, Inc. All rights reserved.
57 Software Engineering Observation 8. 12 Static class variables and methods exist, and can be used, even if no objects of that class have been instantiated. 1992 -2007 Pearson Education, Inc. All rights reserved.
58 Good Programming Practice 8. 1 Invoke every static method by using the class name and a dot (. ) to emphasize that the method being called is a static method. 1992 -2007 Pearson Education, Inc. All rights reserved.
59 2. 3 Employee Example • The employee class has – Two instance variables • firstname, lastname – One static variable to count the employees • count : to count number of employees – A constructor • taking firstname and lastname • incrementing counter by one when creating a new employee – A finalize method • decrementing counter by one when distrcuting an employee object – get method for first and last name – A static get method for counter 1992 -2007 Pearson Education, Inc. All rights reserved.
60 What main does Get counter of Employee class static method without any objcet Generate two employees call get. Counter on each employee and with using class name Pritnt employee information first last names of the two employees Assing the two ref variabe to null e 1 = null; e 2 = null; no more reference to employee objects Ask garbage collector to distroy objcets in memory Print count – number of employees after garbage collector 1992 -2007 Pearson Education, Inc. All rights reserved.
61 Class Employee 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Employee { private String first. Name; private String last. Name; private static int count = 0; // number of objects in memory // initialize employee, add 1 to static count and // output String indicating that constructor was called public Employee( String first, String last ) { first. Name = first; last. Name = last; count++; // increment static count of employees System. out. printf( "Employee constructor: %s %s; count = %d”, first. Name, last. Name, count ); } // end Employee constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
62 Class Employee (cont. ) 23 // subtract 1 from static count when garbage 24 // collector calls finalize to clean up object; 25 // confirm that finalize was called 26 protected void finalize() 27 { 28 count--; // decrement static count of employees 29 System. out. printf( "Employee finalizer: %s %s; count = %dn", 30 first. Name, last. Name, count ); 31 } // end method finalize 32 1992 -2007 Pearson Education, Inc. All rights reserved.
63 Class Employee (cont. ) 33 34 35 36 37 // get first name public String get. First. Name() { return first. Name; } // end method get. First. Name 39 40 41 42 43 44 45 46 47 48 49 50 // get last name public String get. Last. Name() { return last. Name; } // end method get. Last. Name // static method to get static count value public static int get. Count() { return count; } // end method get. Count } // end class Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
64 Class Employee. Test 4 5 6 7 8 9 11 12 13 14 16 17 18 19 20 21 public class Employee. Test { public static void main( String args[] ) { // show that count is 0 before creating Employees System. out. printf( "Employees before instantiation: %dn", Employee. get. Count() ); // create two Employees; count should be 2 Employee e 1 = new Employee( "Susan", "Baker" ); Employee e 2 = new Employee( "Bob", "Blue" ); // show that count is 2 after creating two Employees System. out. println( "n. Employees after instantiation: " ); System. out. printf( "via e 1. get. Count(): %dn", e 1. get. Count() ); System. out. printf( "via e 2. get. Count(): %dn", e 2. get. Count() ); System. out. printf( "via Employee. get. Count(): %dn", Employee. get. Count() ); 1992 -2007 Pearson Education, Inc. All rights reserved.
65 Class Employee. Test (cont. ) 23 // get names of Employees 24 System. out. printf( "n. Employee 1: %s %sn. Employee 2: %s %snn", 25 e 1. get. First. Name(), e 1. get. Last. Name(), 26 e 2. get. First. Name(), e 2. get. Last. Name() ); 27 28 // in this example, there is only one reference to each Employee, 29 // so the following two statements cause the JVM to mark each 30 // Employee object for garbage collection 31 e 1 = null; 32 e 2 = null; 33 34 System. gc(); // ask for garbage collection to occur now 1992 -2007 Pearson Education, Inc. All rights reserved.
66 Class Employee. Test (cont. ) 36 // show Employee count after calling garbage collector; count 37 // displayed may be 0, 1 or 2 based on whether garbage collector 38 // executes immediately and number of Employee objects collected 39 System. out. printf( "n. Employees after System. gc(): %dn", 40 Employee. get. Count() ); 41 } // end main 42 } // end class Employee. Test 1992 -2007 Pearson Education, Inc. All rights reserved.
67 output Employees before instantiation: 0 Employee constructor: Susan Baker; count = 1 Employee constructor: Bob Blue; count = 2 Employees after instantiation: via e 1. get. Count(): 2 via e 2. get. Count(): 2 via Employee. get. Count(): 2 Employee 1: Susan Baker Employee 2: Bob Blue Employee finalizer: Bob Blue; count = 1 Employee finalizer: Susan Baker; count = 0 Employees after System. gc(): 0 1992 -2007 Pearson Education, Inc. All rights reserved.
68 2. 4 static Class Members (cont. ) • String objects are immutable – String concatenation operations actually result in the creation of a new String object • static method gc of class System – Indicates that the garbage collector should make a besteffort attempt to reclaim objects eligible for garbage collection – It is possible that no objects or only a subset of eligible objects will be collected • static methods cannot access non-static class members – Also cannot use this reference 1992 -2007 Pearson Education, Inc. All rights reserved.
69 Common Programming Error 2. 7 A compilation error occurs if a static method calls an instance (non-static) method in the same class by using only the method name. Similarly, a compilation error occurs if a static method attempts to access an instance variable in the same class by using only the variable name. 1992 -2007 Pearson Education, Inc. All rights reserved.
70 Common Programming Error 2. 8 Referring to this in a static method is a syntax error. 1992 -2007 Pearson Education, Inc. All rights reserved.
71 Outline Declare a static field Employee. jav a (1 of 2) Increment static field 1992 -2007 Pearson Education, Inc. All rights reserved.
72 Outline Declare method finalize Employee. jav a (2 of 2) Declare static method get. Count to get static field count 1992 -2007 Pearson Education, Inc. All rights reserved.
73 Employee. Tes t. java Outline (1 of 3) Call static method get. Count using class name Employee Create new Employee objects 1992 -2007 Pearson Education, Inc. All rights reserved.
74 Employee. Tes t. java Outline Call static method get. Count using class name Call static method get. Count using variable name (2 of 3) Remove references to objects, JVM will mark them for garbage collection Call static method gc of class System to indicate that garbage collection should be attempted 1992 -2007 Pearson Education, Inc. All rights reserved.
75 Employee. Tes t. java Outline Call static method get. Count (3 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
76 2. 5 final Instance Variables • Principle of least privilege – Code should have only the privilege and access it needs to accomplish its task, but no more • final instance variables – Keyword final • Specifies that a variable is not modifiable (is a constant) – final instance variables can be initialized at their declaration • If they are not initialized in their declarations, they must be initialized in all constructors 1992 -2007 Pearson Education, Inc. All rights reserved.
77 Software Engineering Observation 3. 13 Declaring an instance variable as final helps enforce the principle of least privilege. If an instance variable should not be modified, declare it to be final to prevent modification. 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 78 Increment. java Declare final instance variable Initialize final instance variable inside a constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 79 Increment. Test. java Create an Increment object Call method add. Increment. Total 1992 -2007 Pearson Education, Inc. All rights reserved.
80 Common Programming Error 3. 10 Attempting to modify a final instance variable after it is initialized is a compilation error. 1992 -2007 Pearson Education, Inc. All rights reserved.
81 Error-Prevention Tip 3. 2 Attempts to modify a final instance variable are caught at compilation time rather than causing execution-time errors. It is always preferable to get bugs out at compilation time, if possible, rather than allow them to slip through to execution time (where studies have found that the cost of repair is often many times more expensive). 1992 -2007 Pearson Education, Inc. All rights reserved.
82 Software Engineering Observation 3. 14 A final field should also be declared static if it is initialized in its declaration. Once a final field is initialized in its declaration, its value can never change. Therefore, it is not necessary to have a separate copy of the field for every object of the class. Making the field static enables all objects of the class to share the final field. 1992 -2007 Pearson Education, Inc. All rights reserved.
83 Common Programming Error 3. 11 Not initializing a final instance variable in its declaration or in every constructor of the class yields a compilation error indicating that the variable might not have been initialized. The same error occurs if the class initializes the variable in some, but not all, of the class’s constructors. 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 84 Increment. java 1992 -2007 Pearson Education, Inc. All rights reserved.
Sending simple types or references to methods 85 • Illustrates the difference betwen methods with a simple type parameter and a reference type parameter • In the test class Test. Exchange 1 main method two integers are created (simple types) • send to the exchange 1 method – expected to interchang the, r values • a beocmes 3, b beocmes 2 1992 -2007 Pearson Education, Inc. All rights reserved.
86 class Test. Exchange 1 public calss Test. Exchange 1 { public static void main(String[] args) { int a = 2; int b = 3; System. out. printf( “in main before excahnge 1: %8 dn”, a, b); exchange 1(a, b); System. out. printf( “in main after excahnge 1: %8 dn”, a, b); } // end of method main 1992 -2007 Pearson Education, Inc. All rights reserved.
87 method exchange 1 public static void exchange 1(int x, int y) { System. out. printf(“in exchange 1 before excahnge of values: %8 dn”, x, y); int temp = x; x = y; y = temp; System. out. printf(“in exchange 1 after excahnge of values: %8 dn”, x, y); } // end of method exchange 1 } // end of class Test. Change 1 1992 -2007 Pearson Education, Inc. All rights reserved.
88 class Test. Exchange 2 public calss Test. Exchange 2 { public static void main(String[] args) { Int a = new Int(2); Int b = new Int(3); System. out. printf(“in main before excahnge 2: %8 dn”, a. get. Val(), b. get. Val()); exchange 2(a, b); System. out. printf(“in main after excahnge 2: %8 dn”, a. get. Val(), b. get. Val()); } // end of method main 1992 -2007 Pearson Education, Inc. All rights reserved.
89 method exchange 2 public static void exchange 2(Int x, Int y) { System. out. printf(“in exchange 2 before excahnge of values: %8 dn”, x. get. Val(), y. get. Val()); int temp = x. get. Val(); x. set. Val(y. get. Val()); y. set. Val(temp); System. out. printf(“in exchange 2 after excahnge of values: %8 dn”, x. get. Val(), y. get. Val()); } // end of method exchange 2 } // end of class Test. Exchange 2 1992 -2007 Pearson Education, Inc. All rights reserved.
90 class Int public class Int { private int val; public Int(int v) { val = v; } public int get. Val() { return val; } public void set. Val(int v) { val = v; } } // end of class Int 1992 -2007 Pearson Education, Inc. All rights reserved.
91 class Test. Exchange 3 // Test class is the same a Test. Exclass 2 // except send a and b to exchange 3 public calss Test. Exchange 3 { public static void main(String[] args) { Int a = new Int(2); Int b = new Int(3); System. out. printf(“in main before excahnge 3: %8 dn”, a. get. Val(), b. get. Val()); exchange 3(a, b); System. out. printf(“in main after excahnge 3: %8 dn”, a. get. Val(), b. get. Val()); } // end of method main 1992 -2007 Pearson Education, Inc. All rights reserved.
92 method exchange 3 public static void exchange 3(Int x, Int y) { System. out. printf(“in exchange 3 before excahnge of values: %8 dn”, x. get. Val(), y. get. Val()); Int temp = x; // object form Int class x = y; y = temp; System. out. printf(“in exchange 3 after excahnge of values: %8 dn”, x. get. Val(), y. get. Val()); } // end of method exchange 3 } // end of class Test. Exchange 3 1992 -2007 Pearson Education, Inc. All rights reserved.
- Slides: 92