1 / 236

Classes and Objects: A Deeper Look

3. Classes and Objects: A Deeper Look. OBJECTIVES. In this chapter you will learn: Encapsulation and data hiding. The notions of data abstraction and abstract data types (ADTs). To use keyword this . To use static variables and methods. To import static members of a class.

mlafferty
Télécharger la présentation

Classes and Objects: A Deeper Look

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 3 • Classes and Objects: A Deeper Look

  2. OBJECTIVES In this chapter you will learn: • Encapsulation and data hiding. • The notions of data abstraction and abstract data types (ADTs). • To use keyword this. • To use static variables and methods. • To import static members of a class. • To use the enum type to create sets of constants with unique identifiers. • How to declare enum constants with parameters.

  3. 8.1    Introduction 8.2Time Class Case Study 8.3    Controlling Access to Members 8.4    Referring to the Current Object’s Members with the this Reference 8.5Time Class Case Study: Overloaded Constructors 8.6    Default and No-Argument Constructors 8.7    Notes on Set and Get Methods 8.8    Composition 8.9    Enumerations 8.10   Garbage Collection and Method finalize

  4. 8.11static Class Members 8.12static Import 8.13final Instance Variables 8.14    Software Reusability 8.15    Data Abstraction and Encapsulation 8.16Time Class Case Study: Creating Packages 8.17    Package Access 8.18    (Optional) GUI and Graphics Case Study: Using Objects with Graphics 8.19    (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System 8.20    Wrap-Up

  5. 3.2  Time Class Case Study • public services (or public interface) • public methods available for a client to use • If a class does not define a constructor the compiler will provide a default constructor • Instance variables • Can be initialized when they are declared or in a constructor • Should maintain consistent (valid) values

  6. Software Engineering Observation 3.1 • Methods that modify the values of private variables should verify that the intended new values are proper. If they are not, the set methods should place the private variables into an appropriate consistent state.

  7. 3.2  Time Class Case Study (Cont.) // Fig. 8.1: Time1.java // Time1 class declaration maintains the time in 24-hour format. public class Time1{ private int hour; // 0 – 23 private int minute; // 0 - 59 private int second; // 0 - 59 // set a new time value using universal time; ensure that // the data remains consistent by setting invalid values to zero public void setTime( int h, int m, int s ){ // Validate parameter values before setting instance variables 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 setTime

  8. 8.2  Time Class Case Study (Cont.) // convert to String in universal-time format (HH:MM:SS) public String toUniversalString(){ return String.format( "%02d:%02d:%02d", hour, minute, second ); } // end method toUniversalString // convert to String in standard-time format (H:MM:SS AM or PM) public String toString(){ return String.format( "%d:%02d:%02d %s", ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } // end method toString } // end class Time1

  9. Methods of the Time1 class • Three instnce variables • Declared as private • Primitve types • Initilized to zero when creating a Time1 objcet • Three methods • public void setTime() • Two of them display time in different formats • public String toUniversalString() • public String toString()

  10. String class’s format method • Stringclass’s method format • Similar to printf except it returns a formatted string instead of displaying it in a command window • new implicitly invokes Time1’s default constructor since Time1 does not declare any constructors

  11. Outline • Time2.java • (1 of 4) No-argument constructor Invoke three-argument constructor

  12. Outline Call setTime method • Time2.java • (2 of 4) Constructor takes a reference to another Time2 object as a parameter Could have directly accessed instance variables of object time here

  13. Outline • Time2.java • (3 of 4)

  14. Outline • Time2.java • (4 of 4)

  15. 3.5  Time Class Case Study: Overloaded Constructors • Overloaded constructors • Provide multiple constructor definitions with different signatures • No-argument constructor • A constructor invoked without arguments • The this reference can be used to invoke another constructor • Allowed only as the first statement in a constructor’s body

  16. class Time overview • Class Time has • 5 constructors • 4 get and set methods • 2 display methods

  17. 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 Time2 object and creates a copy of the object extracting its hour, minute and second values

  18. get and set methods of Time • Class Time has • 4 get and 4 set methods • setTime(int h, int m, int s) • setHour(int h) • setMunite(int m) • setSecond(int s) • 4 get methods • int getHour() • int getMinute() • int getSecond() • Time getTime()

  19. Display methods of Time2 • 2 display methods • toString() • toUniversalString()

  20. Time Class // Time.java // Time class declaration with overloaded constructors. public class Time{ private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time no-argument constructor: initializes each instance variable // to zero; ensures that Time2 objects start in a consistent state public Time() { this( 0, 0, 0 ); // invoke Time constructor with three arguments } // end Time no-argument constructor

  21. Time Class (cont.) // Time constructor: hour supplied, minute and second defaulted to 0 public Time( int h ) { this( h, 0, 0 ); // invoke Time2 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 Time2 constructor with three arguments } // end Time two-argument constructor

  22. Time Class (cont.) // Time constructor: hour, minute and second supplied public Time( int h, int m, int s ){setTime( h, m, s ); // invoke setTime to validate time } // end Time three-argument constructor // Time constructor: another Time2 object supplied public Time( Time time ){ // invoke Time three-argument constructor this( time.getHour(), time.getMinute(), time.getSecond() ); } // end Time constructor with a Time2 object argument

  23. 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 setTime( int h, int m, int s ){ setHour( h ); // set the hour setMinute( m ); // set the minute setSecond( s ); // set the second } // end method setTime

  24. Time Class (cont.) // validate and set hour public void setHour( int h ){ hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // end method setHour // validate and set minute public void setMinute( int m ){ minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // end method setMinute // validate and set second public void setSecond( int s ){ second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // end method setSecond

  25. Time Class (cont.) // Get Methods // get hour value public int getHour(){ return hour; } // end method getHour // get minute value public int getMinute(){ return minute; } // end method getMinute // get second value public int getSecond(){ return second; } // end method getSecond

  26. Time Class (cont.) // convert to String in universal-time format (HH:MM:SS) public String toUniversalString(){ return String.format( "%02d:%02d:%02d", hour, minute, second ); } // end method toUniversalString

  27. Time Class (cont.) // convert to String in standard-time format // (H:MM:SS AM or PM) public String toString(){ return String.format( "%d:%02d:%02d %s", hour==0|| hour==12 ? 12 :hour% 12, minute,second,hour<12 ?"AM":"PM" ); } // end method toString } // end class Time

  28. The format string is First int the hour ( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ), // Second and third int: munite and second getMinute(), getSecond(), // Forth a string either AM or PM ( getHour() < 12 ? "AM" : "PM"

  29. 8.5  Time Class Case Study: Overloaded Constructors 89 // convert to String in universal-time format (HH:MM:SS) 90 public String toUniversalString() 91 { 92 return String.format( 93 "%02d:%02d:%02d", getHour(), getMinute(), getSecond() ); 94 } // end method toUniversalString 95

  30. setTime method public void setTime(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 setTime 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.

  31. ? the ternary operator in Java hour = (( h >= 0 && h < 24 ) ? h : 0 ); ? is the ternary operator in java General form: condition ? expression1 : expresion2; condition is a logical expresion if the condition is true exprsion1 is evaluated else expresion2 is evaluated Equivalent to a clasical if statement as follows: if(condition) variable = expresion1; else variable = expresion2;

  32. ? 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:

  33. ? the ternary operator in Java (cont.) the same expresion can be written in a different form using DeMorgon’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:

  34. 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

  35. method toUniversalString public String toUniversalString() { return String.format( "%02d:%02d:%02d", hour, minute, second ); } // end method toUniversalString "%02d:%02d:%02d“ determines The format %02d an integer two digints 0 means if first is blank fill with 0s

  36. method toUniversalString (cont.) This method can be written like that public String toUniversalString() { String s = String.format( "%02d:%02d:%02d", 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”

  37. method toStriing public String toString() { return String.format( "%d:%02d:%02d %s”, (( hour == 0 || hour == 12 ) ? 12 : hour % 12 minute, second, ( hour < 12 ? "AM" : "PM" ) ); } "%d:%02d:%02d %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

  38. mappings hour 0 1 11 12 13 23 mpapped to 12 1 1112 1 11 AM PM

  39. 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

  40. toString 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

  41. Outline Create a Time1 object • Time1Test.java • (1 of 2) Call toUniversalString method Call toString method

  42. Call setTime method Outline • Time1Test.java • (2 of 2) Call setTime method with invalid values

  43. Test class for using Time Create Time objects default constructor 00:00:00 Set hour munite second Display in universal and standard formats

  44. class TestTime public class Time1Test { public static void main( String args[] ) { // create and initialize a Time1 object Time time = new Time(); // invokes Time1 constructor // output string representations of the time System.out.print( "The initial universal time is: " ); System.out.println( time.toUniversalString() ); System.out.print( "The initial standard time is: " ); System.out.println( time.toString() ); System.out.println(); // output a blank line

  45. class TestTime (cont.) // change time and output updated time time.setTime( 13, 27, 6 ); System.out.print( "Universal time after setTime is: " ); System.out.println( time.toUniversalString() ); System.out.print( "Standard time after setTime is: " ); System.out.println( time.toString() ); System.out.println(); // output a blank line // set time with invalid values; output updated time time.setTime( 99, 99, 99 ); System.out.println( "After attempting invalid settings:" ); System.out.print( "Universal time: " ); System.out.println( time.toUniversalString() ); System.out.print( "Standard time: " ); System.out.println( time.toString() ); } // end main } // end class Time1Test

  46. The output The initial universal time is: 00:00:00 The initial standard time is: 12:00:00 AM Universal time after setTime is: 13:27:06 Standard time after setTime is: 1:27:06 PM After attempting invalid settings: Universal time: 00:00:00 Standard time: 12:00:00 AM

  47. Time t1 = new Time(); // 00:00:00 Time t2 = new Time( 2 ); // 02:00:00 Time t3 = new Time( 21, 34 ); // 21:34:00 Time t4 = new Time( 12, 25, 42 ); // 12:25:42 Time t5 = new Time( 27, 74, 99 ); // 00:00:00 Time t6 = new Time( t4 ); // 12:25:42 t1.setTime( 12, 25, 42 ); // 12:25:42 // these methods to the Time2 class t3.setTime( 6, 11,0); // 06:11:00 t5.setTime(11,0,0); // 11:00:00

  48. Examples of prints System.out.println( "Constructed with:" ); System.out.println( "t1: all arguments defaulted" ); System.out.printf( " %s\n",t1.toUniversalString() ); System.out.printf( " %s\n", t1.toString() ); // toString is not needed it is implecitly // assumed System.out.printf( " %s\n", t1); using the toStrig and toUniversalString methods

  49. output t1: all arguments defaulted 00:00:00 12:00:00 AM t2: hour specified; minute and second defaulted 02:00:00 2:00:00 AM t3: hour and minute specified; second defaulted 21:34:00 9:34:00 PM t4: hour, minute and second specified 12:25:42 12:25:42 PM t5: all invalid values specified 00:00:00 12:00:00 AM t6: Time2 object t4 specified 12:25:42 12:25:42 PM

  50. Outline • Time2Test.java • (1 of 3)

More Related