Object-Based Programming Outline Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Creating Packages Initializing Class Objects: Constructors Using Overloaded Constructors Using Set and Get Methods Software Reusability Final Instance Variables Composition: Objects as Instance Variables of Other Classes Package Access Using the this Reference Finalizers Static Class Members Data Abstraction and Information Hiding Example: Queue Abstract Data Type
63
Embed
Object-Based Programming Outline Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Creating Packages.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Object-Based Programming
OutlineIntroductionImplementing a Time Abstract Data Type with a ClassClass ScopeControlling Access to MembersCreating PackagesInitializing Class Objects: ConstructorsUsing Overloaded ConstructorsUsing Set and Get MethodsSoftware ReusabilityFinal Instance VariablesComposition: Objects as Instance Variables of Other ClassesPackage AccessUsing the this ReferenceFinalizersStatic Class MembersData Abstraction and Information HidingExample: Queue Abstract Data Type
Introduction
• Object-based programming (OBP) – Encapsulates data (attributes) and methods (behavior) into
packages called classes
– Data and methods closely related
– Object-oriented programming • Using inheritance and polymorphism
• Unit of Java programming: the class – A class is like a blueprint – reusable
• Implementation details are hidden within the classes
– Objects are instantiated (created) from the class
Implementing a Time Abstract Data Type with a Class
• In our example– Define two classes, Time1 and TimeTest in separate files
• Only one public class per file
– Time1• Our first non-application, non-applet class
– TimeTest creates a Time1 object• Uses it to display the time
Implementing a Time Abstract Data Type with a Class
– 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– Class body
• Delineated by braces { }• Declare instance variables and methods
6 public class Time1 extends Object {
Implementing a Time Abstract Data Type with a Class
– 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
7 private int hour; // 0 - 238 private int minute; // 0 - 599 private int second; // 0 - 59
Implementing a Time Abstract Data Type with a Class
– Methods• Access methods
– public methods that read/display data– public interface
• Utility methods – private methods that support access methods
21 public void setTime( int h, int m, int s )
29 public String toUniversalString()
Implementing a Time Abstract Data Type with a Class
– Method toString• Of class Object• Takes no arguments, returns a String• Used as a placeholder, usually overridden
– Classes simplify programming• Client only concerned with public operations
• Client not dependent on implementation details
– If implementation changes, client unaffected
– Software reuse
39 public String toString()
Implementing a Time Abstract Data Type with a Class
– Constructor• Special member method
– Same name as the class
• Initializes data members of a class object
• Ensures objects start in consistent state
– Constructors can be overloaded (more later)
– Constructors cannot return values
• No return type, not even void
14 public Time1()
Implementing a Time Abstract Data Type with a Class
– Declarations• Once class defined, can be used as a data type
• Declare objects of the class
• Initialized with constructor
• Use new operator to instantiate a new object
– 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
– Use import when classes not of same package• No import needed for Time1
51 import javax.swing.JOptionPane;
56 Time1 t = new Time1(); // calls Time1 constructor
1. Class Time1 (extends Object)
1.1 private instance variables
1.2 Time1 constructor
2. setTime
1 // Fig. 8.1: Time1.java
2 // Time1 class definition
3 import java.text.DecimalFormat; // used for number formatting
4
5 // This class maintains the time in 24-hour format
66 public class Time1 extends Object {
77 private int hour; // 0 - 23
8 private int minute; // 0 - 59
9 private int second; // 0 - 59
10
11 // Time1 constructor initializes each instance variable
12 // to zero. Ensures that each Time1 object starts in a
13 // consistent state.
1414 public Time1()
15 {
16 setTime( 0, 0, 0 );
17 }
18
19 // Set a new time value using universal time. Perform
20 // validity checks on the data. Set invalid values to zero.
2121 public void setTime( int h, int m, int s )
22 {
23 hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
24 minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
25 second = ( ( s >= 0 && s < 60 ) ? s : 0 );
26 }
27
Each file needs exactly one public class, which is the filename. Time1 inherits from class Object.
private instance variables can only be accessed by methods in their class.
Time1 constructor, initializes new Time1 objects.
public method, may be accessed through a Time1 reference. Checks validity of arguments.
2.1 toUniversalString
2.2 toString
28 // Convert to String in universal-time format
29 public String toUniversalString()
30 {
31 DecimalFormat twoDigits = new DecimalFormat( "00" );
32
33 return twoDigits.format( hour ) + ":" +
34 twoDigits.format( minute ) + ":" +
35 twoDigits.format( second );
36 }
37
38 // Convert to String in standard-time format
3939 public String toString()
40 {
41 DecimalFormat twoDigits = new DecimalFormat( "00" );
Method toString inherited from class Object and is overridden. Takes no arguments, implicitly knows to use instance variables of the object that invoked it.
1. import
2. main
2.1 Create new Time1 object
2.2 t.setTime
49 // Fig. 8.1: TimeTest.java
50 // Class TimeTest to exercise class Time1
51 import javax.swing.JOptionPane;
52
53 public class TimeTest {
54 public static void main( String args[] )
55 {
56 Time1 t = new Time1(); // calls Time1 constructor
57 String output;
58
59 output = "The initial universal time is: " +
60 t.toUniversalString() +
61 "\nThe initial standard time is: " +
62 t.toString() +
63 "\nImplicit toString() call: " + t;
64
65 t.setTime( 13, 27, 6 ); 66 output += "\n\nUniversal time after setTime is: " + 67 t.toUniversalString() +68 "\nStandard time after setTime is: " +69 t.toString();7071 t.setTime( 99, 99, 99 ); // all invalid values72 output += "\n\nAfter attempting invalid settings: " + 73 "\nUniversal time: " + t.toUniversalString() +74 "\nStandard time: " + t.toString();
Class Time1 needs no import because it is in same package.
Declares t a reference to a Time1 object, and creates a new object.
Call method setTime using reference t. Note dot operator.
Program Output
75
76 JOptionPane.showMessageDialog( null, output,
77 "Testing Class Time1",
78 JOptionPane.INFORMATION_MESSAGE );
79
80 System.exit( 0 );
81 }
82 }
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 handleobjectReferenceName.variableName
objectReferenceName.methodName()
• 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)
Controlling Access to Members
• Purpose of public – Give clients a view of the services the class provides
(interface)
• Purpose of private– Default setting
– Hide details of how the class accomplishes its tasks (implementation)
– Private members only accessible through the public interface using public member methods
• Upcoming program– Attempt to access a private variable using a reference
1. Create new Time1 object
1.1 t.hour
Program Output
1 // Fig. 8.2: TimeTest.java
2 // Demonstrate errors resulting from attempts
3 // to access private class members.
4 public class TimeTest {
5 public static void main( String args[] )
6 {
7 Time1 t = new Time1();
8
99 t.hour = 7;
10 }
11 }
TimeTest.java:9: Variable hour in class Time1 not accessible from class TimeTest. t.hour = 7; ^1 error
Attempt to access a private instance variable of class Time1.
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 own structure
package com.deitel.jhtp3.ch08; – See text for detailed instructions
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• Can have constructor with no arguments
– Declaration/initialization of new objects:ref = new ClassName( 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
Initializing Class Objects: Constructors
• Upcoming example– Redo Time1 class
– Provide several constructors
15 public Time2() { setTime( 0, 0, 0 ); }
19 public Time2( int h ) { setTime( h, 0, 0 ); }
23 public Time2( int h, int m ) { setTime( h, m, 0 ); }
26 public Time2( int h, int m, int s ) { setTime( h, m, s ); }
1. package
1.1 Class Time2
1.2 Instance variables
1.3 Constructors
1 // Fig. 8.4: Time2.java
2 // Time2 class definition
33 package com.deitel.jhtp3.ch08; // place Time2 in a package
4 import java.text.DecimalFormat; // used for number formatting
5
6 // This class maintains the time in 24-hour format
7 public class Time2 extends Object {
8 private int hour; // 0 - 23
9 private int minute; // 0 - 59
10 private int second; // 0 - 59
11
12 // Time2 constructor initializes each instance variable
13 // to zero. Ensures that Time object starts in a
14 // consistent state.
1515 public Time2() { setTime( 0, 0, 0 ); }
16
17 // Time2 constructor: hour supplied, minute and second
18 // defaulted to 0.
19 public Time2( int h ) { setTime( h, 0, 0 ); }
20
21 // Time2 constructor: hour and minute supplied, second
22 // defaulted to 0.
23 public Time2( int h, int m ) { setTime( h, m, 0 ); }
24
25 // Time2 constructor: hour, minute and second supplied.
26 public Time2( int h, int m, int s ) { setTime( h, m, s ); }
27
Class Time2 is placed into a package
Notice the overloaded constructors. The proper one is called depending on the number of arguments.
2. Methods
28 // Time2 constructor: another Time2 object supplied.
80 t6 = new Time2( t4 ); // use t4 as initial value
81
82 output = "Constructed with: " +
83 "\nt1: all arguments defaulted" +
84 "\n " + t1.toUniversalString() +
85 "\n " + t1.toString();
86
87 output += "\nt2: hour specified; minute and " +
88 "second defaulted" +
89 "\n " + t2.toUniversalString() +
90 "\n " + t2.toString();
91
Initialize Time2 objects using the overloaded constructors.
2.2 Display
92 output += "\nt3: hour and minute specified; " +
93 "second defaulted" +
94 "\n " + t3.toUniversalString() +
95 "\n " + t3.toString();
96
97 output += "\nt4: hour, minute, and second specified" +
98 "\n " + t4.toUniversalString() +
99 "\n " + t4.toString();
100
101 output += "\nt5: all invalid values specified" +
102 "\n " + t5.toUniversalString() +
103 "\n " + t5.toString();
104
105 output += "\nt6: Time2 object t4 specified" +
106 "\n " + t6.toUniversalString() +
107 "\n " + t6.toString();
108
109 JOptionPane.showMessageDialog( null, output,
110 "Demonstrating Overloaded Constructors",
111 JOptionPane.INFORMATION_MESSAGE );
112
113 System.exit( 0 );
114 }
115}
Program Output
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
• If implementation changes– Clients can still use same methods
– Do not know implementation details
Using Set and Get Methods
– Every event has a source• GUI component with which user interacted• ActionEvent parameter can check its source
• Method getSource
– Method getActionCommand• Returns String containing text in JTextField when user
hit Enter
141 public void actionPerformed( ActionEvent e )142 {143 if ( e.getSource() == tickButton )144 tick();
145 else if ( e.getSource() == hourField ) {
146 t.setHour(
147 Integer.parseInt( e.getActionCommand() ) );
148 hourField.setText( "" );
1. package
2. Class Time3
2.1 Constructors
1 // Fig. 8.5: Time3.java
2 // Time3 class definition
3 package com.deitel.jhtp3.ch08; // place Time3 in a package
4 import java.text.DecimalFormat; // used for number formatting
5
6 // This class maintains the time in 24-hour format
7 public class Time3 extends Object {
8 private int hour; // 0 - 23
9 private int minute; // 0 - 59
10 private int second; // 0 - 59
11
12 // Time3 constructor initializes each instance variable
13 // to zero. Ensures that Time object starts in a
14 // consistent state.
15 public Time3() { setTime( 0, 0, 0 ); }
16
17 // Time3 constructor: hour supplied, minute and second
18 // defaulted to 0.
19 public Time3( int h ) { setTime( h, 0, 0 ); }
20
21 // Time3 constructor: hour and minute supplied, second
22 // defaulted to 0.
23 public Time3( int h, int m ) { setTime( h, m, 0 ); }
24
25 // Time3 constructor: hour, minute and second supplied.
26 public Time3( int h, int m, int s ) { setTime( h, m, s ); }
27
2.2 Set methods
28 // Time3 constructor: another Time3 object supplied.29 public Time3( Time3 time )30 {31 setTime( time.getHour(),32 time.getMinute(),33 time.getSecond() );34 }3536 // Set Methods37 // Set a new time value using universal time. Perform 38 // validity checks on the data. Set invalid values to zero.39 public void setTime( int h, int m, int s )40 {41 setHour( h ); // set the hour42 setMinute( m ); // set the minute43 setSecond( s ); // set the second44 }4546 // set the hour
4747 public void setHour( int h ) 48 { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); }49
50 // set the minute
51 public void setMinute( int m )
52 { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); }
53
54 // set the second
55 public void setSecond( int s )
56 { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }
57
The public set methods allow clients to change private data members. However, inputs are validated.
2.3 Get methods
58 // Get Methods59 // get the hour6060 public int getHour() { return hour; }6162 // get the minute63 public int getMinute() { return minute; }6465 // get the second66 public int getSecond() { return second; }6768 // Convert to String in universal-time format69 public String toUniversalString()70 {71 DecimalFormat twoDigits = new DecimalFormat( "00" );7273 return twoDigits.format( getHour() ) + ":" +74 twoDigits.format( getMinute() ) + ":" +75 twoDigits.format( getSecond() );76 }7778 // Convert to String in standard-time format79 public String toString()80 {81 DecimalFormat twoDigits = new DecimalFormat( "00" );8283 return ( ( getHour() == 12 || getHour() == 0 ) ? 84 12 : getHour() % 12 ) + ":" +85 twoDigits.format( getMinute() ) + ":" +86 twoDigits.format( getSecond() ) +87 ( getHour() < 12 ? " AM" : " PM" );88 }89 }
Get methods allow clients to view selected private data.
1. import
2. GUI
90 // Fig. 8.5: TimeTest.java91 // Demonstrating the Time3 class set and get methods92 import java.awt.*;93 import java.awt.event.*;94 import javax.swing.*;95 import com.deitel.jhtp3.ch08.Time3;9697 public class TimeTest extends JApplet98 implements ActionListener {99 private Time3 t;100 private JLabel hourLabel, minuteLabel, secondLabel;101 private JTextField hourField, minuteField,102 secondField, display;103 private JButton tickButton;104105 public void init()106 {107 t = new Time3();108109 Container c = getContentPane();110111 c.setLayout( new FlowLayout() );112 hourLabel = new JLabel( "Set Hour" );113 hourField = new JTextField( 10 );114 hourField.addActionListener( this );115 c.add( hourLabel );116 c.add( hourField );117118 minuteLabel = new JLabel( "Set minute" );119 minuteField = new JTextField( 10 );120 minuteField.addActionListener( this );
2. GUI
3. Event handler (actionPerformed)
121 c.add( minuteLabel );122 c.add( minuteField );123124 secondLabel = new JLabel( "Set Second" );125 secondField = new JTextField( 10 );126 secondField.addActionListener( this );127 c.add( secondLabel );128 c.add( secondField );129130 display = new JTextField( 30 );131 display.setEditable( false );
132 c.add( display );
133
134 tickButton = new JButton( "Add 1 to Second" );
135 tickButton.addActionListener( this );
136 c.add( tickButton );
137
138 updateDisplay();
139 }
140
141 public void actionPerformed( ActionEvent e )142 {143 if ( e.getSource() == tickButton )144 tick();145 else if ( e.getSource() == hourField ) {146 t.setHour(147 Integer.parseInt( e.getActionCommand() ) );148 hourField.setText( "" );149 }
Use method getSource to find which button was pushed.
Use method getActionCommand to get the text the user input.
4. Method updateDisplay
150 else if ( e.getSource() == minuteField ) {
151 t.setMinute(
152 Integer.parseInt( e.getActionCommand() ) );
153 minuteField.setText( "" );
154 }
155 else if ( e.getSource() == secondField ) {
156 t.setSecond(
157 Integer.parseInt( e.getActionCommand() ) );
158 secondField.setText( "" );
159 }
160
161 updateDisplay();
162 }
163
164 public void updateDisplay()
165 {
166 display.setText( "Hour: " + t.getHour() +
167 "; Minute: " + t.getMinute() +
168 "; Second: " + t.getSecond() );
169 showStatus( "Standard time is: " + t.toString() +
170 "; Universal time is: " + t.toUniversalString() );
171 }
172
5. Method tick
Program Output
173 public void tick()
174 {
175 t.setSecond( ( t.getSecond() + 1 ) % 60 );
176
177 if ( t.getSecond() == 0 ) {
178 t.setMinute( ( t.getMinute() + 1 ) % 60 );
179
180 if ( t.getMinute() == 0 )
181 t.setHour( ( t.getHour() + 1 ) % 24 );
182 }
183 }
184}
Program Output
Program Output
Final Instance Variables
• Principle of least privilege– Each component has enough access to accomplish its task,
nothing more
– Prevents accidental/malicious errors
• Keyword final– Used for non-modifiable instance variables
private final int INCREMENT = 5;– final variables must be initialized at declaration
– Use all capital letters in name
Composition: Objects as Instance Variables of Other Classes
• Composition– Class has references to other objects as members
– Default constructor automatically called
– Example:
AlarmClock object has a Time object as a member
• Upcoming example– Class Date
• Instance variables month, day, year
– Class Employee• Instance variables firstName, lastName• Composition: has Date references birthDate, hireDate
1. Class Date
1.1 Instance variables
1.2 Constructor
1 // Fig. 8.8: Date.java
2 // Declaration of the Date class.
3 package com.deitel.jhtp3.ch08;
4
5 public class Date extends Object {
6 private int month; // 1-12
7 private int day; // 1-31 based on month
8 private int year; // any year
9
10 // Constructor: Confirm proper value for month;
11 // call method checkDay to confirm proper
12 // value for day.
13 public Date( int mn, int dy, int yr )
14 {
15 if ( mn > 0 && mn <= 12 ) // validate the month
16 month = mn;
17 else {
18 month = 1;
19 System.out.println( "Month " + mn +
20 " invalid. Set to month 1." );
21 }
22
23 year = yr; // could also check
24 day = checkDay( dy ); // validate the day
25
2626 System.out.println(
27 "Date object constructor for date " + toString() );
Can call getCount even though no object of class Employee exist.
Call getCount using Employee references.
2.4 Employee.getCount()
59 // mark objects referred to by e1 and e260 // for garbage collection61 e1 = null; 62 e2 = null;6364 System.gc(); // suggest that garbage collector be called
65
66 output += "\n\nEmployees after System.gc(): " +
6767 Employee.getCount();
68
69 JOptionPane.showMessageDialog( null, output,
70 "Static Members and Garbage Collection",
71 JOptionPane.INFORMATION_MESSAGE );
72 System.exit( 0 );
73 }
74 }
Once the objects are destroyed, must call getCount through the class.
Program Output
Employee object constructor: Susan BakerEmployee object constructor: Bob JonesEmployee object finalizer: Susan Baker; count = 1Employee object finalizer: Bob Jones; count = 0
Data Abstraction and Information Hiding
• Java– Focus on creating new data type (classes)
• Abstract Data Types (ADTs)– Ways to represent real-world notions