2.32k likes | 2.36k Views
8. 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.
E N D
8 • 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. • To use the enum type to create sets of constants with unique identifiers. • How to declare enum constants with parameters.
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
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
8.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
Software Engineering Observation 8.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.
8.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.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
Methods of the Time 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()
8.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
Outline • Time2.java • (1 of 4) No-argument constructor Invoke three-argument constructor
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
Outline • Time2.java • (3 of 4)
Outline • Time2.java • (4 of 4)
class Time overview • Class Time has • 5 constructors • 4 get and set methods • 2 display methods
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
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()
Display methods of Time2 • 2 display methods • toString() • toUniversalString()
8.5 Time Class Case Study: Overloaded Constructors // 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
8.5 Time Class Case Study: Overloaded Constructors // 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
8.5 Time Class Case Study: Overloaded Constructors // 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
8.5 Time Class Case Study: Overloaded Constructors // 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
// 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
8.5 Time Class Case Study: Overloaded Constructors // 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
8.5 Time Class Case Study: Overloaded Constructors // 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
8.5 Time Class Case Study: Overloaded Constructors // 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
The format string is "%d:%02d:%02d %s", // what to format three int one string 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"
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
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 Time1 objcet aster the object’s creation with new via default constrfuctor.
? 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;
? 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:
? 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:
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
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
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
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”
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: ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) Second and third are just munite and second Forth is a stirng either AM or PM
First argument ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) İf hour is 0 or 12 12 is returned else hour mod 12 is returned Example Time:00:15:20 to 12:15:20 AM :05:15:20 to 5:15:20 AM as 5 % 12 = 5 :12:15:20 to 12:15:20 PM :21:15:20 to 9:15:20 PM as 21 % 12 = 9
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
Outline Create a Time1 object • Time1Test.java • (1 of 2) Call toUniversalString method Call toString method
Call setTime method Outline • Time1Test.java • (2 of 2) Call setTime method with invalid values
Test class for using Time1 Create Time1 objects default constructor 00:00:00 Set hour munite second Display in universal and standard formats
4 public class Time1Test 5 { 6 public static void main( String args[] ) 7 { 8 // create and initialize a Time1 object 9 Time1 time = new Time1(); // invokes Time1 constructor 10 11 // output string representations of the time 12 System.out.print( "The initial universal time is: " ); 13 System.out.println( time.toUniversalString() ); 14 System.out.print( "The initial standard time is: " ); 15 System.out.println( time.toString() ); 16 System.out.println(); // output a blank line 17
18 // change time and output updated time 19 time.setTime( 13, 27, 6 ); 20 System.out.print( "Universal time after setTime is: " ); 21 System.out.println( time.toUniversalString() ); 22 System.out.print( "Standard time after setTime is: " ); 23 System.out.println( time.toString() ); 24 System.out.println(); // output a blank line 25 26 // set time with invalid values; output updated time 27 time.setTime( 99, 99, 99 ); 28 System.out.println( "After attempting invalid settings:" ); 29 System.out.print( "Universal time: " ); 30 System.out.println( time.toUniversalString() ); 31 System.out.print( "Standard time: " ); 32 System.out.println( time.toString() ); 33 } // end main 34 } // end class Time1Test
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
8.3 Controlling Access to Members • A class’s public interface • public methods a view of the services the class provides to the class’s clients • A class’s implementation details • private variables and private methods are not accessible to the class’s clients
Common Programming Error 8.1 • An attempt by a method that is not a member of a class to access a private member of that class is a compilation error.
Outline • MemberAccessTest • .java Attempting to access private instance variables
8.4 Referring to the Current Object’s Members with the this Reference 3 public class MemberAccessTest 4 { 5 public static void main( String args[] ) 6 { 7 Time1 time = new Time1(); // create and initialize Time1 object 8 9 time.hour = 7;// error: hour has private access in Time1 10 time.minute = 15;// error: minute has private access in Time1 11 time.second = 30;// error: second has private access in Time1 12 } // end main 13 } // end class MemberAccessTest
output MemberAccessTest.java:9: hour has private access in Time1 time.hour = 7; // error: hour has private access in Time1 ^ MemberAccessTest.java:10: minute has private access in Time1 time.minute = 15; // error: minute has private access in Time1 ^ MemberAccessTest.java:11: second has private access in Time1 time.second = 30; // error: second has private access in Time1 ^ 3 errors