Chapter 8 ObjectBased Programming Outline 8 1 8
Chapter 8 – Object-Based Programming Outline 8. 1 8. 2 8. 3 8. 4 8. 5 8. 6 8. 7 8. 8 8. 9 8. 10 8. 11 8. 12 8. 13 8. 14 8. 15 8. 16 Introduction Implementing a Time Abstract Data Type with a Class Scope Controlling Access to Members Referring to the Current Object’s Members with this Initializing Class Objects: Constructors Using Overloaded Constructors Using Set and Get Methods Composition Garbage Collection Static Class Members Final Instance Variables Creating Packages Package Access Software Reusability Data Abstraction and Encapsulation 2003 Prentice Hall, Inc. All rights reserved. 1
2 8. 1 Introduction • Object Oriented Programming (OOP) – Encapsulates data (attributes) and methods (behaviors) • Objects – Allows objects to communicate • Well-defined interfaces – Information hiding 2003 Prentice Hall, Inc. All rights reserved.
3 8. 1 Introduction (cont. ) • Procedural programming language – C is an example – Action-oriented – Functions are units of programming • Object-oriented programming language – Java is an example – Object-oriented – Classes are units of programming • Functions, or methods, are encapsulated in classes 2003 Prentice Hall, Inc. All rights reserved.
4 8. 1 Introduction (cont. ) • Object Based Programming = creating and using classes and objects • Object Oriented Programming = Inheritance and Polymorphism 2003 Prentice Hall, Inc. All rights reserved.
8. 2 Implementing a Time Abstract Data Type with a Class • We introduce classes Time 1 and Time. Test – – Time 1. java declares class Time 1 Time. Test. java declares class Time. Test public classes must be declared in separate files Class Time 1 will not execute by itself • Does not have method main • Time. Test, which has method main, creates (instantiates) and uses Time 1 object • Time. Test. java does NOT import Time 1 – import not needed for class in same package (directory) 2003 Prentice Hall, Inc. All rights reserved. 5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 8. 1: Time 1. java // Time 1 class declaration maintains the time in 24 -hour format. import java. text. Decimal. Format; Time 1 (subclass) public class Time 1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 Outline 6 extends superclass java. lang. Object (Chapter 9 discusses inheritance) Time 1. java 5 private variables (and. Line methods) are Time 1 accessible only to methods in this(subclass) class // Time 1 constructor initializes each instance variable to zero; extends superclass // ensures that each Time 1 object starts in a consistent state java. lang. Objec public Time 1() t { set. Time( 0, 0, 0 ); Lines 6 -8 } Time 1 constructor creates private variables Lines 12 -15 // set a new time value using universal time; Time 1 perform object then invokes Time 1 constructor // validity checks on the data; set invalid valuesmethod to zeroset. Time then invokes method public void set. Time( int h, int m, int s ) { set. Time hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); Line 19 minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); Method set. Time sets private public methods (andpublic variables) methods variables according to arguments second = ( ( s >= 0 && s < 60 ) ? s : 0 ); are accessible wherever program Lines 19 -24 } has Time 1 reference Method set. Time sets private variables according to arguments 2003 Prentice Hall, Inc. All rights reserved.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // convert to String in universal-time format public String to. Universal. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Outline return two. Digits. format( hour ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ); } // convert to String in standard-time format public String to. Standard. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ) + ( hour < 12 ? " AM" : " PM" ); Time 1. java } } // end class Time 1 2003 Prentice Hall, Inc. All rights reserved. 7
8. 2 Implementing a Time Abstract Data Type with a Class (cont. ) • Every Java class must extend another class – Time 1 extends java. lang. Object – If class does not explicitly extend another class, class implicitly extends Object • Class constructor – – – Same name as class Initializes instance variables of a class object Called when program instantiates an object of that class Can take arguments, but cannot return values Class can have several constructors through overloading Class Time 1 constructor (lines 12 -15) 2003 Prentice Hall, Inc. All rights reserved. 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 8. 2: Time. Test 1. java Declare and create instance of class // Class Time. Test 1 to exercise class Time 1 by calling Time 1 constructor import javax. swing. JOption. Pane; Outline 9 public class Time. Test 1 { public static void main( String args[] ) { Time. Test 1 Time 1 time = new Time 1(); // calls Time 1 constructor interacts with Time 1 Time. Test 1. java by calling Time 1 public methods // append String version of time to String output = "The initial universal time is: " + time. to. Universal. String() + "n. The initial standard time is: " + time. to. Standard. String(); // change time and append updated time to output time. set. Time( 13, 27, 6 ); output += "nn. Universal time after set. Time is: " + time. to. Universal. String() + "n. Standard time after set. Time is: " + time. to. Standard. String(); // set time with invalid values; append updated time to output time. set. Time( 99, 99 ); output += "nn. After attempting invalid settings: " + "n. Universal time: " + time. to. Universal. String() + "n. Standard time: " + time. to. Standard. String(); Line 9 Declare and create instance of class Time 1 by calling Time 1 constructor Lines 12 -26 Time. Test 1 interacts with Time 1 by calling Time 1 public methods 2003 Prentice Hall, Inc. All rights reserved.
28 29 30 31 32 33 34 35 JOption. Pane. show. Message. Dialog( null, output, "Testing Class Time 1", JOption. Pane. INFORMATION_MESSAGE ); Outline 10 System. exit( 0 ); } // end main } // end class Time. Test 1. java 2003 Prentice Hall, Inc. All rights reserved.
11 8. 3 Class Scope • Class scope – Class variables and methods – Members are accessible to all class methods – Members can be referenced by name 2003 Prentice Hall, Inc. All rights reserved.
12 8. 4 Controlling Access to Members • Member access modifiers – Control access to class’s variables and methods – public • Variables and methods accessible to clients of the class – private • Variables and methods not accessible to clients of the class • Typical = private data members and public methods 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Fig. 8. 3: Time. Test 2. java // Errors resulting from attempts to access private members of Time 1. public class Time. Test 2 { Outline 13 public static void main( String args[] ) { Time 1 time = new Time 1(); time. hour = 7; // error: hour is a private instance variable time. minute = 15; // error: minute is a private instance variable time. second = 30; // error: second is a private instance variable } } // end class Time. Test 2. java Compiler error – Time. Test 2 cannot directly access Time 1’s private data Lines 9 -11 Time. Test 2. java: 9: hour has private access in Time 1 time. hour = 7; // error: hour is a private instance variable Compiler error – Time. Test 2 cannot directly access Time 1’s private data ^ Time. Test 2. java: 10: minute has private access in Time 1 time. minute = 15; // error: minute is a private instance variable ^ Time. Test 2. java: 11: second has private access in Time 1 time. second = 30; // error: second is a private instance variable ^ 3 errors 2003 Prentice Hall, Inc. All rights reserved.
8. 5 Referring to the Current Object’s Members with this • Keyword this – Allows an object to refer to itself – this refers to the object for which the method was called – More important use later for things like supervisor. ID = this. ID; 2003 Prentice Hall, Inc. All rights reserved. 14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8. 4: This. Test. java // Using the this reference to refer to instance variables and methods. import javax. swing. *; import java. text. Decimal. Format; Outline public class This. Test { public static void main( String args[] ) { Simple. Time time = new Simple. Time( 12, 30, 19 ); JOption. Pane. show. Message. Dialog( null, time. build. String(), "Demonstrating the "this" Reference", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); This. Test. java } } // end class This. Test // class Simple. Time demonstrates the "this" reference class Simple. Time { private int hour; private int minute; private int second; 2003 Prentice Hall, Inc. All rights reserved. 15
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // constructor uses parameter names identical to instance variable // names; "this" reference required to distinguish between names public Simple. Time( int hour, int minute, int second ) { this. hour = hour; // set "this" object's this hour used to distinguish this. minute = minute; // set "this" object's minute between arguments and this. second = second; // set "this" object's second This. Test variables } // use explicit and implicit "this" to call to. Standard. String public String build. String() { return "this. to. Standard. String(): " + this. to. Standard. String() + "nto. Standard. String(): " + to. Standard. String(); } Outline 16 This. Test. java Lines 31 -33 this used to distinguish between arguments Use explicit and implicit this variables // return String representation of Simple. Time to call to. Standard. String public String to. Standard. String() Lines 39 -40 { Decimal. Format two. Digits = new Decimal. Format( "00" ); use explicit and implicit this to call // "this" is not required here, because method does not to. Standars. String // have local variables with same names as instance variables return two. Digits. format( this. hour ) + ": " + two. Digits. format( this. minute ) + ": " + two. Digits. format( this. second ); } } // end class Simple. Time 2003 Prentice Hall, Inc. All rights reserved.
17 8. 6 Initializing Class Objects: Constructors • Class constructor – Same name as class – Initializes instance variables of a class object – Call class constructor to instantiate object of that class new Class. Name( argument 1, argument 2, …, arugment. N ); • new indicates that new object is created • Class. Name indicates type of object created • arguments specifies constructor argument values – If no constructor declared, compiler creates default constructor – If any constructor(s) declared, compiler does not create default constructor 2003 Prentice Hall, Inc. All rights reserved.
18 8. 7 Using Overloaded Constructors • Overloaded constructors – Methods (in same class) may have same name – Must have different signatures (parameter lists) – To call one constructor from another… this (parameters); …which must be the first statement of the constructor – Calling one constructor from another is a little inefficient, but an excellent idea in case the object representation changes 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 8. 5: Time 2. java // Time 2 class declaration with overloaded constructors. import java. text. Decimal. Format; public class Time 2 { private int hour; private int minute; private int second; // 0 - 23 // 0 - 59 No-argument (default) constructor Outline 19 Time 2. java Use this to invoke the Time 2 constructor declared at lines 30 -33 Lines 12 -15 // Time 2 constructor initializes each instance variable to zero; No-argument (default) // ensures that Time object starts in a consistent state constructor public Time 2() Line 14 { Overloaded constructor this( 0, 0, 0 ); // invoke Time 2 constructor withint three arguments Use this to invoke the has one argument } Time 2 constructor declared at lines 30 -33 // Time 2 constructor: hour supplied, minute and second defaulted to 0 Lines 18 -21 public Time 2( int h ) Second overloaded constructor Overloaded { has two int arguments this( h, 0, 0 ); // invoke Time 2 constructor with three arguments constructor has one } int argument Lines 24 -27 // Time 2 constructor: hour and minute supplied, second defaulted to 0 Second overloaded public Time 2( int h, int m ) { constructor has two this( h, m, 0 ); // invoke Time 2 constructor with three arguments int arguments } 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 Outline // Time 2 constructor: hour, minute and second supplied public Time 2( int h, int m, int s ) Third overloaded constructor { has three int arguments set. Time( h, m, s ); // invoke set. Time to validate time } // Time 2 constructor: another Time 2 object supplied public Time 2( Time 2 time ) { // invoke Time 2 constructor with three arguments this( time. hour, time. minute, time. second ); Fourth overloaded } constructor has Time 2 argument // set a new time value using universal time; perform // validity checks on data; set invalid values to zero public void set. Time( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // convert to String in universal-time format public String to. Universal. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Time 2. java Lines 30 -33 Third overloaded constructor has three int arguments Lines 36 -40 Fourth overloaded constructor has Time 2 argument return two. Digits. format( hour ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ); } 2003 Prentice Hall, Inc. All rights reserved. 20
59 60 61 62 63 64 65 66 67 68 69 70 // convert to String in standard-time format public String to. Standard. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Outline return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ) + ( hour < 12 ? " AM" : " PM" ); } } // end class Time 2. java 2003 Prentice Hall, Inc. All rights reserved. 21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Outline // Fig. 8. 6: Time. Test 3. java // Overloaded constructors used to initialize Time 2 objects. import javax. swing. *; 22 public class Time. Test 3 { public static { Time 2 t 1 = Time 2 t 2 = Time 2 t 3 = Time 2 t 4 = Time 2 t 5 = Time 2 t 6 = void main( String args[] ) new new new String output "nt 1: all "n " Time 2(); Time 2( 21, 34 ); Time 2( 12, 25, 42 ); Time 2( 27, 74, 99 ); Time 2( t 4 ); // // // Instantiate each Time 2 reference using a different constructor 00: 00 02: 00 21: 34: 00 12: 25: 42 00: 00 12: 25: 42 = "Constructed with: " + arguments defaulted" + + t 1. to. Universal. String() + + t 1. to. Standard. String(); Time. Test 3. java Lines 9 -14 Instantiate each Time 2 reference using a different constructor output += "nt 2: hour specified; minute and second defaulted" + "n " + t 2. to. Universal. String() + "n " + t 2. to. Standard. String(); output += "nt 3: hour and minute specified; second defaulted" + "n " + t 3. to. Universal. String() + "n " + t 3. to. Standard. String(); 2003 Prentice Hall, Inc. All rights reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 output += "nt 4: hour, minute and second specified" + "n " + t 4. to. Universal. String() + "n " + t 4. to. Standard. String(); Outline 23 output += "nt 5: all invalid values specified" + "n " + t 5. to. Universal. String() + "n " + t 5. to. Standard. String(); output += "nt 6: Time 2 object t 4 specified" + "n " + t 6. to. Universal. String() + "n " + t 6. to. Standard. String(); JOption. Pane. show. Message. Dialog( null, output, "Overloaded Constructors", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); Time. Test 3. java } // end main } // end class Time. Test 3 2003 Prentice Hall, Inc. All rights reserved.
24 8. 8 Using Set and Get Methods • Accessor method (“get” method) – public method – Allow clients to access private data – BUT, class creator decides which private data to make available • Mutator method (“set” method) – public method – Allow clients to modify private data – BUT, class creator decides which private data to make modifiable and to control how it is modified (validity checking) 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 8. 7: Time 3. java // Time 3 class declaration with set and get methods. import java. text. Decimal. Format; public class Time 3 { private int hour; private int minute; private int second; // 0 - 23 // 0 - 59 Outline 25 private variables cannot be accessed directly by objects in differentto classes instance variable zero; // Time 3 constructor initializes each // ensures that Time object starts in a consistent state public Time 3() { this( 0, 0, 0 ); // invoke Time 3 constructor with three arguments } // Time 3 constructor: hour supplied, minute and second defaulted to 0 public Time 3( int h ) { this( h, 0, 0 ); // invoke Time 3 constructor with three arguments } Time 3. java Lines 6 -8 private variables cannot be accessed directly by objects in different classes // Time 3 constructor: hour and minute supplied, second defaulted to 0 public Time 3( int h, int m ) { this( h, m, 0 ); // invoke Time 3 constructor with three arguments } 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // Time 3 constructor: hour, minute and second supplied public Time 3( int h, int m, int s ) { set. Time( h, m, s ); } Outline 26 // Time 3 constructor: another Time 3 object supplied public Time 3( Time 3 time ) { // invoke Time 3 constructor with three arguments this( time. get. Hour(), time. get. Minute(), time. get. Second() ); } // Set Methods // set a new time value using universal time; perform // validity checks on data; set 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 } Time 3. java Lines 45 -68 methods allows Set methods. Set allows objects tovariables manipulate private variables // validate and set hour public void set. Hour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } 2003 Prentice Hall, Inc. All rights reserved.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 // validate and set minute public void set. Minute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } Outline // validate and set second public void set. Second( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // Get Methods // get hour value public int get. Hour() { return hour; } // get minute value public int get. Minute() { return minute; } Time 3. java Get methods allow objects to read private variables Lines 72 -87 Get methods allow objects to read private variables 2003 Prentice Hall, Inc. All rights reserved. 27
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 // get second value public int get. Second() { return second; } Outline // convert to String in universal-time format public String to. Universal. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); return two. Digits. format( get. Hour() ) + ": " + two. Digits. format( get. Minute() ) + ": " + two. Digits. format( get. Second() ); } // convert to String in standard-time format public String to. Standard. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Time 3. java return ( ( get. Hour() == 12 || get. Hour() == 0 ) ? 12 : get. Hour() % 12 ) + ": " + two. Digits. format( get. Minute() ) + ": " + two. Digits. format( get. Second() ) + ( get. Hour() < 12 ? " AM" : " PM" ); } } // end class Time 3 2003 Prentice Hall, Inc. All rights reserved. 28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Outline // Fig. 8. 8: Time. Test 4. java // Demonstrating the Time 3 class set and get methods. import java. awt. *; import java. awt. event. *; import javax. swing. *; 29 public class Time. Test 4 extends JApplet implements Action. Listener { private Time 3 time; Declare and instantiate private JLabel hour. Label, minute. Label, second. Label; Time 3 objectdisplay. Field; private JText. IField hour. Field, minute. Field, second. Field, private JButton tick. Button; // create Time 3 object and set up GUI public void init() { time = new Time 3(); // create Time 3 object Time. Test 4. java Lines 8 and 17 Declare and instantiate Time 3 object // get applet's content pane and change its layout to Flow. Layout Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); // set up hour. Label and hour. Field hour. Label = new JLabel( "Set Hour" ); hour. Field = new JText. Field( 10 ); container. add( hour. Label ); container. add( hour. Field ); Lines 25 and 31 JText. Field allows user to specify hour 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // set up minute. Label and minute. Field minute. Label = new JLabel( "Set Minute" ); minute. Field = new JText. Field( 10 ); container. add( minute. Label ); container. add( minute. Field ); // set up second. Label and second. Field second. Label = new JLabel( "Set Second" ); second. Field = new JText. Field( 10 ); container. add( second. Label ); container. add( second. Field ); Outline 30 JText. Field allows user to specify minute JText. Field allows user to specify second // set up display. Field = new JText. Field( 30 ); display. Field. set. Editable( false ); container. add( display. Field ); // set up tick. Button = new JButton( "Add 1 to Second" ); container. add( tick. Button ); // register event handlers; this applet is the Action. Listener, // which contains method action. Performed that will be called to // handle action events generated by hour. Field, minute. Field, // second. Field and tick. Button hour. Field. add. Action. Listener( this ); minute. Field. add. Action. Listener( this ); second. Field. add. Action. Listener( this ); tick. Button. add. Action. Listener( this ); Time. Test 4. java Line 31 JText. Field allows user to specify minute Line 37 JText. Field allows user to specify second 2003 Prentice Hall, Inc. All rights reserved.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 display. Time(); // update text in display. Field and status bar Outline 31 } // end method init // event handler for button and textfield events public void action. Performed( Action. Event event ) { // process tick. Button event if ( event. get. Source() == tick. Button ) tick(); // process hour. Field event else if ( event. get. Source() == hour. Field ) { time. set. Hour( Integer. parse. Int( event. get. Action. Command() ) ); hour. Field. set. Text( "" ); } Time. Test 4. java Lines 71 -74 Lines 77 -80 Lines 83 -86 Time. Test 5 uses // process minute. Field event Time 3 set methods to else if ( event. get. Source() == minute. Field ) { set Time 3 private time. set. Minute( Integer. parse. Int( event. get. Action. Command() ) ); minute. Field. set. Text( "" ); variables Time. Test 5 uses Time 3 set methods to } set Time 3 private variables // process second. Field event else if ( event. get. Source() == second. Field ) { time. set. Second( Integer. parse. Int( event. get. Action. Command() ) ); second. Field. set. Text( "" ); } 2003 Prentice Hall, Inc. All rights reserved.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 display. Time(); // update text in display. Field and status bar Outline 32 } // end method action. Performed // update display. Field and applet container's status bar public void display. Time() { display. Field. set. Text( "Hour: " + time. get. Hour() + "; Minute: " + time. get. Minute() + "; Second: " + time. get. Second() ); show. Status( "Standard time is: " + time. to. Standard. String() + "; Universal time is: " + time. to. Universal. String() ); } // end method update. Display // add one to second and update hour/minute public void tick() { time. set. Second( ( time. get. Second() + 1 ) Time. Test 4. java Lines 95 -96 if necessary Time. Test 5 uses Time 3 Time. Test 5 get methods uses to Time 3 get methods to read Time 3 private variables read Time 3 % 60 ); private variables if ( time. get. Second() == 0 ) { time. set. Minute( ( time. get. Minute() + 1 ) % 60 ); if ( time. get. Minute() == 0 ) time. set. Hour( ( time. get. Hour() + 1 ) % 24 ); } } // end method tick } // end class Time. Test 4 2003 Prentice Hall, Inc. All rights reserved.
Outline 33 Time. Test 4. java 2003 Prentice Hall, Inc. All rights reserved.
Outline 34 Time. Test 4. java 2003 Prentice Hall, Inc. All rights reserved.
Outline 35 Time. Test 4. java 2003 Prentice Hall, Inc. All rights reserved.
36 8. 9 Composition • Composition – Class contains references to objects of other classes • These references are members • Neither class is a subclass of the other 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8. 9: Date. java // Date class declaration. public class Date { private int month; private int day; private int year; 37 Outline Class Date encapsulates data that describes date // 1 -12 // 1 -31 based on month // any year // constructor: call check. Month to confirm proper value for month; Date. java // call check. Day to confirm proper value for day public Date( int the. Month, int the. Day, int the. Year ) Line 4 { Class Date month = check. Month( the. Month ); // validate month year = the. Year; // could validate year encapsulates data day = check. Day( the. Day ); // validate day. Date constructor instantiates describes date System. out. println( "Date object constructor for to. Date. String() ); } // end Date constructor that Date object based on date " + specified arguments Lines 11 -20 Date constructor instantiates Date object based on specified arguments // 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; 2003 Prentice Hall, Inc. All rights reserved.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 else { // month is invalid System. out. println( "Invalid month (" + test. Month + ") set to 1. " ); return 1; // maintain object in consistent state } Outline } // end method check. Month // utility method to confirm proper day value based on month and year private int check. Day( int test. Day ) { int days. Per. Month[] = { 0, 31, 28, 31, 30, 31 }; // check if day in range for month if ( test. Day > 0 && test. Day <= days. Per. Month[ month ] ) return test. Day; Date. java // check for leap year if ( month == 2 && test. Day == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) return test. Day; System. out. println( "Invalid day (" + test. Day + ") set to 1. " ); return 1; // maintain object in consistent state } // end method check. Day 2003 Prentice Hall, Inc. All rights reserved. 38
56 57 58 59 60 61 62 63 // return a String of the form month/day/year public String to. Date. String() { return month + "/" + day + "/" + year; } Outline } // end class Date. java 2003 Prentice Hall, Inc. All rights reserved. 39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Outline // Fig. 8. 10: Employee. java // Employee class declaration. public class Employee { private String first. Name; private String last. Name; private Date birth. Date; private Date hire. Date; Employee is composed of two references to Date objects // constructor to initialize name, birth date and hire date public Employee( String first, String last, Date date. Of. Birth, Date date. Of. Hire ) { first. Name = first; last. Name = last; birth. Date = date. Of. Birth; hire. Date = date. Of. Hire; } Employee. java Lines 7 -8 Employee is composed of two references to Date objects // convert Employee to String format public String to. Employee. String() { return last. Name + ", " + first. Name + " Hired: " + hire. Date. to. Date. String() + " Birthday: " + birth. Date. to. Date. String(); } } // end class Employee 40 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Fig. 8. 11: Employee. Test. java // Demonstrating an object with a member object. import javax. swing. JOption. Pane; Outline 41 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", "Jones", birth, hire ); JOption. Pane. show. Message. Dialog( null, employee. to. Employee. String(), "Testing Class Employee", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } Employee. Test. ja va } // end class Employee. Test Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 2003 Prentice Hall, Inc. All rights reserved.
42 8. 10 Garbage Collection • Memory no longer accessible is called a “memory leak” • Garbage collection – Returns memory to system – Java performs this automagically • object marked for garbage collection if no references to object • Finalizer method (called a “destructor” in C++) – Returns resources to system – Java provides method finalize • Defined in java. lang. Object • Receives no parameters • Returns void 2003 Prentice Hall, Inc. All rights reserved.
43 8. 11 Static Class Members • Each object has its own copy of all the class instance variables • static keyword – static class variable – Class-wide information – All class objects share same copy of this data • Access to a class’s public static members – Qualify the member name with the class name • e. g. , Math. random() – Can also use any object name • e. g. , e 3. get. Count() 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Fig. 8. 12: Employee. java // Employee class declaration. public class Employee { private String first. Name; private String last. Name; private static int count = 0; Outline Employee objects share one instance of count // 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. println( "Employee constructor: " + first. Name + " " + last. Name ); } 44 Employee. java Line 6 Employee objects share one instance of count Lines 23 -28 Called when Employee is Called when marked for garbage collection garbage collector Employee is marked and output String for garbage collection // subtract 1 from static count when // calls finalize to clean up object // indicating that finalize was called protected void finalize() { --count; // decrement static count of employees System. out. println( "Employee finalizer: " + first. Name + " " + last. Name + "; count = " + count ); } 2003 Prentice Hall, Inc. All rights reserved.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 Outline // get first name public String get. First. Name() { return first. Name; } // get last name public String get. Last. Name() { return last. Name; } static method accesses static variable count // static method to get static count value public static int get. Count() { return count; } Employee. java Lines 43 -46 static method accesses static variable count } // end class Employee 2003 Prentice Hall, Inc. All rights reserved. 45
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 8. 13: Employee. Test. java // Test Employee class with static class variable, // static class method, and dynamic memory. import javax. swing. *; public class Employee. Test { Outline 46 Employee. Test can invoke Employee static method, even though Employee has not been instantiated public static void main( String args[] ) { // prove that count is 0 before creating Employees String output = "Employees before instantiation: " + Employee. get. Count(); // create two Employees; count should be 2 Employee e 1 = new Employee( "Susan", "Baker" ); Employee e 2 = new Employee( "Bob", "Jones" ); // prove that count is 2 after creating two Employees output += "nn. Employees after instantiation: " + "nvia e 1. get. Count(): " + e 1. get. Count() + "nvia e 2. get. Count(): " + e 2. get. Count() + "nvia Employee. get. Count(): " + Employee. get. Count(); Employee. Test. ja va Line 12 Employee. Test can invoke Employee static method, even though Employee has not been instantiated // get names of Employees output += "nn. Employee 1: " + e 1. get. First. Name() + " " + e 1. get. Last. Name() + "n. Employee 2: " + e 2. get. First. Name() + " " + e 2. get. Last. Name(); 2003 Prentice Hall, Inc. All rights reserved.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 // // // e 1 e 2 decrement reference count for each Employee object; in this example, there is only one reference to each Employee, so these statements mark each Employee object for garbage collection Calls Java’s automatic garbage= null; collection mechanism = null; Outline 47 System. gc(); // suggest call to garbage collector // show Employee count after calling garbage collector; count // displayed may be 0, 1 or 2 based on whether garbage collector // executes immediately and number of Employee objects collected output += "nn. Employees after System. gc(): " + Employee. get. Count(); JOption. Pane. show. Message. Dialog( null, output, "Static Members", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } Employee. Test. ja va Line 35 Calls Java’s automatic garbage-collection mechanism } // end class Employee. Test Employee constructor: Susan Baker constructor: Bob Jones finalizer: Susan Baker; count = 1 finalizer: Bob Jones; count = 0 2003 Prentice Hall, Inc. All rights reserved.
48 8. 12 Final Instance Variables • final keyword (similar to const in C++) – Indicates that variable is not modifiable • Any attempt to modify final variable results in error private final int INCREMENT = 5; • Declares variable INCREMENT as a constant – Enforces principle of least privilege – Standard programming practice is to capitalize such a constant 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Fig. 8. 14: Increment. Test. java // Initializing a final variable. import java. awt. *; import java. awt. event. *; import javax. swing. *; Outline 49 public class Increment. Test extends JApplet implements Action. Listener { private Increment increment. Object; private JButton button; // set up GUI public void init() { increment. Object = new Increment( 5 ); Container container = get. Content. Pane(); Increment. Test. j ava button = new JButton( "Click to increment" ); button. add. Action. Listener( this ); container. add( button ); } // add INCREMENT to total when user clicks button public void action. Performed( Action. Event action. Event ) { increment. Object. increment(); show. Status( increment. Object. to. Increment. String() ); } } // end class Increment. Test 2003 Prentice Hall, Inc. All rights reserved.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // class containing constant variable class Increment { private int count = 0; // number of increments private int total = 0; // total of all increments final private final int INCREMENT; // constant variable Outline 50 keyword declares INCREMENT as constant // initialize constant INCREMENT public Increment( int increment. Value ) { INCREMENT = increment. Value; // intialize constant variable (once) } // add INCREMENT to total and add 1 to count public void increment() final variable INCREMENT must { total += INCREMENT; be initialized before using it ++count; } // return String representation of an Increment object's data public String to. Increment. String() { return "After increment " + count + ": total = " + total; } Increment. java Line 36 final keyword declares INCREMENT as constant Line 41 final variable INCREMENT must be initialized before using it } // end class Increment 2003 Prentice Hall, Inc. All rights reserved.
51 Increment. Test. java: 40: variable INCREMENT might not have been initialized { ^ 1 error 2003 Prentice Hall, Inc. All rights reserved.
52 8. 13 Creating Packages • We can import packages into programs – – Group of related classes and interfaces Help manage complexity of application components Facilitate software reuse Provide convention for unique class names • Popular package-naming convention – Reverse Internet domain name • e. g. , com. deitel 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 8. 16: Time 1. java // Time 1 class declaration maintains the time in 24 -hour format. Class Time 1 is placed package com. deitel. jhtp 5. ch 08; in this package Outline 53 import java. text. Decimal. Format; public class Time 1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 Class Time 1 is in directory com/deitel/jhtp 5/ch 08 // Time 1 constructor initializes each instance variable to zero; // ensures that each Time 1 object starts in a consistent state import class Decimal. Format public Time 1() { from package java. text set. Time( 0, 0, 0 ); } // set a new time value using universal time; perform // validity checks on the data; set invalid values to zero public void set. Time( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } Time 1. java Line 3 Class Time 1 is placed in this package Line 3 Class Time 1 is in directory com/deitel/jhtp 5/ch 08 Line 5 import class Decimal. Format from package java. text 2003 Prentice Hall, Inc. All rights reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // convert to String in universal-time format public String to. Universal. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Outline Decimal. Format from package java. text return two. Digits. format( hour ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ); } // convert to String in standard-time format public String to. Standard. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Time 1. java return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ) + ( hour < 12 ? " AM" : " PM" ); } } // end class Time 1 Line 31 Decimal. Format from package java. text 2003 Prentice Hall, Inc. All rights reserved. 54
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8. 17: Time. Test 1. java // Class Time. Test 1 to exercise class Time 1. // Java packages import javax. swing. JOption. Pane; // Deitel packages import com. deitel. jhtp 5. ch 08. Time 1; Outline 55 import class JOption. Pane from package javax. swing // import Time 1 class Time. Test 1. java Line 5 import class Time 1 from package import class com. deitel. jhtp 4. ch 08 void main( String args[] ) JOption. Pane from package = new Time 1(); // calls Time 1 constructor javax. swing public class Time. Test 1 { public static { Time 1 time // append String version of time to String output = "The initial Time. Test 1 universal time is: " + can declare Time 1 object time. to. Universal. String() + "n. The initial standard time is: " + time. to. Standard. String(); // change time and append updated time to output time. set. Time( 13, 27, 6 ); output += "nn. Universal time after set. Time is: " + time. to. Universal. String() + "n. Standard time after set. Time is: " + time. to. Standard. String(); Line 8 import class Time 1 from package com. deitel. jhtp 4. ch 08 Line 14 Time. Test 1 can declare Time 1 object 2003 Prentice Hall, Inc. All rights reserved.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 // set time with invalid values; append updated time to output time. set. Time( 99, 99 ); output += "nn. After attempting invalid settings: " + "n. Universal time: " + time. to. Universal. String() + "n. Standard time: " + time. to. Standard. String(); Outline 56 JOption. Pane. show. Message. Dialog( null, output, "Testing Class Time 1", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } // end main } // end class Time. Test 1. java 2003 Prentice Hall, Inc. All rights reserved.
57 8. 14 Package Access • Package access – Variable or method does not have member access modifier 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8. 18: Package. Data. Test. java // Classes in the same package (i. e. , the same directory) can // use package access data of other classes in the same package. Instantiate import javax. swing. JOption. Pane; Outline 58 reference to Package. Data object public class Package. Data. Test { public static void main( String args[] ) { Package. Data package. Data = new Package. Data(); Package. Data. Test. java Line 10 Instantiate reference to // append String representation of package. Data to output Package. Data String output = "After instantiation: n" + package. Data. to. Package. Data. String(); Package. Data. Testobject can access Package. Data // change package access data in package. Data object Lines 13 -22 data, because each class package. Data. number = 77; Package. Data. Test shares same package. Data. string = "Goodbye"; can access Package. Data data, // append String representation of package. Data to output because each class output += "n. After changing values: n" + shares same package. Data. to. Package. Data. String(); JOption. Pane. show. Message. Dialog( null, output, "Package Access", JOption. Pane. INFORMATION_MESSAGE ); 2003 Prentice Hall, Inc. All rights reserved.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 Outline System. exit( 0 ); 59 } } // end class Package. Data. Test // class with package access instance variables class Package. Data { int number; // package-access instance variable String string; // package-access instance variable // constructor public Package. Data() { number = 0; string = "Hello"; } No access modifier, so class has package-access variables Package. Data. Test. // return Package. Data object String representation public String to. Package. Data. String() { return "number: " + number + " string: " + string; } java Line 33 No access modifier, so class has packageaccess variables } // end class Package. Data 2003 Prentice Hall, Inc. All rights reserved.
60 8. 15 Software Reusability • Java – Framework for achieving software reusability – Rapid applications development (RAD) • e. g. , creating a GUI application quickly 2003 Prentice Hall, Inc. All rights reserved.
61 8. 16 Data Abstraction and Encapsulation • Information hiding – Stack data structure • Last in-first out (LIFO) • Like cafeteria trays on a spring-loaded platform • Developer creates stack – Hides stack’s implementation details from clients – Interface are methods push, pop, top, is. Empty? • Data abstraction – Abstract data types (ADTs) 2003 Prentice Hall, Inc. All rights reserved.
8. 16 Data Abstraction and Encapsulation (Cont. ) • Abstract Data Type (ADT) – Queue • Like line at grocery store checkout • First-in, first-out (FIFO) – Enqueue to place objects in queue – Dequeue to remove object from queue – Enqueue and dequeue hide internal data representation 2003 Prentice Hall, Inc. All rights reserved. 62
- Slides: 62