Chapter 26 Java ObjectBased Programming Outline 26 1
Chapter 26 - Java Object-Based Programming Outline 26. 1 Introduction 26. 2 Implementing a Time Abstract Data Type with a Class 26. 3 Class Scope 26. 4 Creating Packages 26. 5 Initializing Class Objects: Constructors 26. 6 Using Set and Get Methods 26. 7 Using the this Reference 26. 8 Finalizers 26. 9 Static Class Members 2000 Prentice Hall, Inc. All rights reserved.
26. 1 Introduction • Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior) into packages called classes – Data and functions closely related • Information hiding – Implementation details are hidden within the classes themselves • Unit of Java programming: the class – – A class is like a blueprint – reusable Objects are instantiated (created) from the class For example, a house is an instance of a “blueprint class” C programmers concentrate on functions 2000 Prentice Hall, Inc. All rights reserved.
26. 2 Implementing a Time Abstract Data Type with a Class • In our example – Define two classes, Time 1 and Time. Test in separate files • Only one public class per file • Class definitions – Never really create definition from scratch • Use extends to inherit data and methods from base class • Derived class: class that inherits – Every class in Java subclass of Object • Gets useful methods, discussed later – Class body • Delineated by braces { } • Declare instance variables and methods 2000 Prentice Hall, Inc. All rights reserved.
26. 2 Implementing a Time Abstract Data Type with a Class (II) • Member-access modifiers – public: accessible whenever program has a reference to an object of the class – private: accessible only to member methods of that class – Member variables are usually private • Methods – Access methods: public methods that read/display data • public interface • Clients use references to interact with objects – Utility methods: private methods that support access methods 2000 Prentice Hall, Inc. All rights reserved.
26. 2 Implementing a Time Abstract Data Type with a Class (II) • Constructor – Special member function • Same name as the class – Initializes data members of a class object – Constructors cannot return values • Declarations – Once class defined, can be used as a data type – Declare objects of the class Time 1 my. Time. Object = new my. Time 1(); • Declares object, initializes with constructor 2000 Prentice Hall, Inc. All rights reserved.
26. 2 Implementing a Time Abstract Data Type with a Class (III) • import – If no package specified for class, class put in default package • Includes compiled classes of current directory – If class in same package as another, import not required – import when classes not of same package • Classes simplify programming – Client only concerned with public operations – Client not dependent on implementation details • If implementation changes, client unaffected – Software reuse 2000 Prentice Hall, Inc. All rights reserved.
26. 2 Implementing a Time Abstract Data Type with a Class (IV) • Method to. String – Class Object – Takes no arguments, returns a String – Used as a placeholder, usually overridden • Class Decimal. Format (java. text) – Create object of class, initialize with format control string Decimal. Format two. Digits = new Decimal. Format( "00" ); – Each 0 is a placeholder for a digit • Prints in form 08, 10, 15. . . – Method format returns String with proper formatting two. Digits. format( my. Int ); 2000 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 // Fig. 26. 1: Time 1. java // Time 1 class definition import java. text. Decimal. Format; // used for number formatting // This class maintains the time in 24 -hour format public class Time 1 extends Object { private int hour; private int minute; private int second; // 0 - 23 // 0 - 59 // Time 1 constructor initializes each instance variable // to zero. Ensures that each Time 1 object starts in a // consistent state. public Time 1() { 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 ); } // Convert to String in universal-time format public String to. Universal. String() { 2000 Prentice Hall, Inc. All rights reserved. Outline 1. import 1. 1 Class definition extends Object 1. 2 Constructor (same name as class) 1. 3 Method to. Universal. String
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 } Decimal. Format two. Digits = new Decimal. Format( "00" ); return two. Digits. format( hour ) + ": " + two. Digits. format( minute ) + ": " + two. Digits. format( second ); } // Convert to String in standard-time format public String to. 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" ); } 2000 Prentice Hall, Inc. All rights reserved. Outline 1. 4 "00" signifies two digits to be printed 2. Override to. String
49 50 51 52 53 54 55 56 57 58 59 60 // Fig. 26. 1: Time. Test. java // Class Time. Test to exercise class Time 1 import javax. swing. JOption. Pane; public class Time. Test { public static void main( String args[] ) { Time 1 t = new Time 1(); // calls Time 1 constructor String output; output = "The initial universal time is: " + t. to. Universal. String() + 61 "n. The initial standard time is: " + 62 t. to. String() + 63 "n. Implicit to. String() call: " + t; 64 65 t. set. Time( 13, 27, 6 ); 66 output += "nn. Universal time after set. Time is: " + 67 t. to. Universal. String() + 68 "n. Standard time after set. Time is: " + 69 t. to. String(); 70 71 t. set. Time( 99, 99 ); // all invalid values 72 output += "nn. After attempting invalid settings: " + 73 "n. Universal time: " + t. to. Universal. String() + 74 "n. Standard time: " + t. to. String(); 75 2000 Prentice Hall, Inc. All rights reserved. Outline 1. import JOption. Pane (no need to import Time 1) 2. main 2. 1 to. String called implicitly to make object of correct type
76 JOption. Pane. show. Message. Dialog( null, output, 77 78 79 80 81 "Testing Class Time 1", JOption. Pane. INFORMATION_MESSAGE ); Outline System. exit( 0 ); } 82 } Program Output 2000 Prentice Hall, Inc. All rights reserved.
26. 3 Class Scope • Class scope – Instance variables and methods – Class members accessible to methods • Can be referenced by name – Outside scope, cannot be referenced by name – Visible (public) members accessed through a handle object. Reference. Name. Variable. Name • Block scope – Variables defined in a method known only to that method – If variable has same name as class variable, class variable hidden – Can be accessed using keyword this (discussed later) 2000 Prentice Hall, Inc. All rights reserved.
26. 4 Creating Packages • Packages – Directory structures that organize classes and interfaces – Mechanism for software reuse • Creating packages – Create a public class • If not public, can only be used by classes in same package – Choose a package name and add a package statement to source code file – Compile class (placed into appropriate directory) – Import into other programs Naming: Internet domain name in reverse order • After name reversed, choose your own structure package com. deitel. chtp 3. ch 26; – See text for detailed instructions 2000 Prentice Hall, Inc. All rights reserved.
26. 5 Initializing Class Objects: Constructors • Constructor – – – Can initialize members of an object Cannot have return type Class may have overloaded constructors Initializers passed as arguments to constructor Declaration/initialization of new objects takes form: ref = new Class. Name( arguments ); • Constructor has same name as class – If no constructor defined, compiler makes default constructor • Defaults: 0 for primitive numeric types, false for boolean, null for references • If constructor defined, no default constructor – Can have constructor with no arguments 2000 Prentice Hall, Inc. All rights reserved.
26. 6 Using Set and Get Methods • Set methods – public method that sets private variables – Does not violate notion of private data • Change only the variables you want – Called mutator methods (change value) • Get methods – public method that displays private variables – Again, does not violate notion of private data • Only display information you want to display – Called accessor or query methods 2000 Prentice Hall, Inc. All rights reserved.
26. 6 Using Set and Get Methods (II) • Every event has a source – GUI component with which user interacted – Action. Event parameter can check its source • Method get. Source public void action. Performed( Action. Event e ) if ( e. get. Source() == my. Button ) 2000 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 // Fig. 26. 3: Time 2. java // Time 2 class definition package com. deitel. chtp 3. ch 26; import java. text. Decimal. Format; // place Time 2 in a package // used for number formatting // This class maintains the time in 24 -hour format public class Time 2 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time 2 constructor initializes each instance variable // to zero. Ensures that Time object starts in a // consistent state. public Time 2() { set. Time( 0, 0, 0 ); } // Set Methods // 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 ) { set. Hour( h ); // set the hour set. Minute( m ); // set the minute set. Second( s ); // set the second } // set the hour public void set. Hour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } 2000 Prentice Hall, Inc. All rights reserved. Outline 1. package statement 1. 1 import 1. 2 Constructor 1. 3 Method definitions
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 59 60 // set the minute public void set. Minute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // set the second public void set. Second( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } // Get Methods // get the hour public int get. Hour() { return hour; } // get the minute public int get. Minute() { return minute; } // get the second public int get. Second() { return second; } // 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. String() 2000 Prentice Hall, Inc. All rights reserved. Outline 1. 3 Method definitions (notice get and set methods)
61 { 62 Decimal. Format two. Digits = new Decimal. Format( "00" ); Outline 63 64 return ( ( get. Hour() == 12 || get. Hour() == 0 ) ? 65 12 : get. Hour() % 12 ) + ": " + 66 two. Digits. format( get. Minute() ) + ": " + 67 two. Digits. format( get. Second() ) + 68 ( get. Hour() < 12 ? " AM" : " PM" ); 69 } 70 } 2000 Prentice Hall, Inc. All rights reserved. 1. 3 Method definitions
71 // Fig. 26. 3: Time. Test. java 72 73 74 75 76 // Demonstrating the Time 2 class set and get methods import java. awt. *; import java. awt. event. *; import javax. swing. *; import com. deitel. chtp 3. ch 26. Time 2; 77 78 public class Time. Test extends JApplet 79 implements Action. Listener { 80 81 82 private Time 2 t; private JLabel hour. Label, minute. Label, second. Label; private JText. Field hour. Field, minute. Field, 83 84 second. Field, display; private JButton tick. Button; 85 86 87 public void init() { 88 t = new Time 2(); 89 90 91 92 93 94 95 96 97 98 99 100 Container c = get. Content. Pane(); c. set. Layout( new Flow. Layout() ); hour. Label = new JLabel( "Set Hour" ); hour. Field = new JText. Field( 10 ); hour. Field. add. Action. Listener( this ); c. add( hour. Label ); c. add( hour. Field ); minute. Label = new JLabel( "Set minute" ); minute. Field = new JText. Field( 10 ); 2000 Prentice Hall, Inc. All rights reserved. Outline 1. import (notice package containing Time 2) 1. 1 implements Action. Listener
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 minute. Field. add. Action. Listener( this ); c. add( minute. Label ); c. add( minute. Field ); second. Label = new JLabel( "Set Second" ); second. Field = new JText. Field( 10 ); second. Field. add. Action. Listener( this ); c. add( second. Label ); c. add( second. Field ); display = new JText. Field( 30 ); display. set. Editable( false ); c. add( display ); tick. Button = new JButton( "Add 1 to Second" ); tick. Button. add. Action. Listener( this ); c. add( tick. Button ); update. Display(); } public void action. Performed( Action. Event e ) { if ( e. get. Source() == tick. Button ) tick(); else if ( e. get. Source() == hour. Field ) { t. set. Hour( Integer. parse. Int( e. get. Action. Command() ) ); hour. Field. set. Text( "" ); } 2000 Prentice Hall, Inc. All rights reserved. Outline 2. Define action. Performed 2. 1 Notice e. get. Source
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 else if ( e. get. Source() t. set. Minute( Integer. parse. Int( minute. Field. set. Text( } else if ( e. get. Source() t. set. Second( Integer. parse. Int( second. Field. set. Text( } == minute. Field ) { e. get. Action. Command() ) ); "" ); == second. Field ) { e. get. Action. Command() ) ); "" ); update. Display(); } public void update. Display() { display. set. Text( "Hour: " + t. get. Hour() + "; Minute: " + t. get. Minute() + "; Second: " + t. get. Second() ); show. Status( "Standard time is: " + t. to. String() + "; Universal time is: " + t. to. Universal. String() ); } public void tick() { t. set. Second( ( t. get. Second() + 1 ) % 60 ); if ( t. get. Second() == 0 ) { t. set. Minute( ( t. get. Minute() + 1 ) % 60 ); 2000 Prentice Hall, Inc. All rights reserved. Outline 2. 2 Method definitions
161 if ( t. get. Minute() == 0 ) 162 t. set. Hour( ( t. get. Hour() + 1 ) % 24 ); 163 164 Outline } } 165 } 2000 Prentice Hall, Inc. All rights reserved. 2. 2 Method definitions
Outline Program Output 2000 Prentice Hall, Inc. All rights reserved.
26. 7 Using the this Reference • Each object has a reference to itself – The this reference • Implicitly used to refer to instance variables and methods • Inside methods – If parameter has same name as instance variable • Instance variable hidden – Use this. variable. Name to explicitly refer to the instance variable – Use variable. Name to refer to the parameter 2000 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 // Fig. 26. 4: This. Test. java // Using the this reference to refer to // instance variables and methods. import javax. swing. *; import java. text. Decimal. Format; public class This. Test { public static void main( String args[] ) { Simple. Time t = new Simple. Time( 12, 30, 19 ); JOption. Pane. show. Message. Dialog( null, t. build. String(), "Demonstrating the "this" Reference", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } class Simple. Time { private int hour, minute, second; public Simple. Time( int hour, int minute, int second ) { this. hour = hour; this. minute = minute; this. second = second; } public String build. String() 2000 Prentice Hall, Inc. All rights reserved. Outline 1. import 2. main 2. 1 Initialize object 2. 2 Define class 2. 3 Constructor (note use of this)
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 } { return "this. to. String(): " + this. to. String() + "nto. String(): " + to. String() + "nthis (with implicit to. String() call): " + this; } public String to. String() { Decimal. Format two. Digits = new Decimal. Format( "00" ); Outline 2. 4 Method definitions (note use of this) return two. Digits. format( this. hour ) + ": " + two. Digits. format( this. minute ) + ": " + two. Digits. format( this. second ); } Program Output 2000 Prentice Hall, Inc. All rights reserved.
26. 8 Finalizers • Memory – Constructors use memory when creating new objects – Automatic garbage collection • When object no longer used, object marked for garbage collection • Garbage collector executes, memory can be reclaimed • Memory leaks less common in Java than in C and C++ • finalizer method – In every class, returns resources to system • Performs termination housekeeping on object – Name always finalize • Takes no parameters, returns no value – Defined in class Object as a placeholder • Every class gets a finalize method 2000 Prentice Hall, Inc. All rights reserved.
26. 9 Static Class Members • Static variables – Usually, each object gets its own copy of each variable – static class variables shared among all objects of the class • One copy exists for entire class to use – – Keyword static Only have class scope (not global) static class variables exist even when no objects do public static members accessed through references or class name and dot operator – private static members accessed through methods • If no objects exist, classname and public static method must be used 2000 Prentice Hall, Inc. All rights reserved.
26. 9 Static Class Members (II) • static methods – Can only access class static members – static methods have no this reference • static variables are independent of objects • Method gc – public static method of class System – Suggests garbage collector execute immediately • Can be ignored • Garbage collector not guaranteed to collect objects in a specific order 2000 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. 26. 5: Employee. java // Declaration of the Employee class. public class Employee extends Object { private String first. Name; private String last. Name; private static int count; // # of objects in memory public Employee( String f. Name, String l. Name ) { first. Name = f. Name; last. Name = l. Name; ++count; // increment static count of employees System. out. println( "Employee object constructor: " + first. Name + " " + last. Name ); Outline 1. Class definition 1. 1 static variable 1. 2 Constructor 1. 3 Method finalize } 1. 4 Get methods protected void finalize() { --count; // decrement static count of employees System. out. println( "Employee object finalizer: " + first. Name + " " + last. Name + "; count = " + count ); } public String get. First. Name() { return first. Name; } public String get. Last. Name() { return last. Name; } public static int get. Count() { return count; } } 2000 Prentice Hall, Inc. All rights reserved.
32 // Fig. 8. 12: Employee. Test. java 33 34 35 36 37 // Test Employee class with static class variable, // static class method, and dynamic memory. import javax. swing. *; public class Employee. Test { 38 public static void main( String args[] ) 39 40 { String output; 41 42 43 output = "Employees before instantiation: " + Employee. get. Count(); 44 45 Employee e 1 = new Employee( "Susan", "Baker" ); 46 47 48 Employee e 2 = new Employee( "Bob", "Jones" ); output += "nn. Employees after instantiation: " + 49 "nvia e 1. get. Count(): " + e 1. get. Count() + 50 51 "nvia e 2. get. Count(): " + e 2. get. Count() + "nvia Employee. get. Count(): " + 52 53 54 55 56 57 Employee. get. Count(); 58 59 60 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(); // mark objects referred to by e 1 and e 2 // for garbage collection 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Class definition 1. 1 Initialize objects
61 e 1 = null; 62 e 2 = null; Outline 63 64 System. gc(); // suggest that garbage collector be called 65 66 output += "nn. Employees after System. gc(): " + 67 2. System. gc Employee. get. Count(); 68 69 JOption. Pane. show. Message. Dialog( null, output, 70 "Static Members and Garbage Collection", 71 JOption. Pane. INFORMATION_MESSAGE ); 72 System. exit( 0 ); 73 } 74 } Program Output 2000 Prentice Hall, Inc. All rights reserved.
- Slides: 33