8.5 Referring to the Current Object’s Members with thisKeyword this (this reference)
Allows an object to refers to itself
Lecture 5Chapter 8 – Object-Based Programming
Outline8.1 Introduction8.2 Implementing a Time Abstract Data Type with a Class8.3 Class Scope8.4 Controlling Access to Members8.5 Referring to the Current Object’s Members with this 8.6 Initializing Class Objects: Constructors 8.7 Using Overloaded Constructors8.8 Using Set and Get Methods8.9 Composition 8.10 Garbage Collection 8.11 Static Class Members 8.12 Final Instance Variables 8.13 Creating Packages 8.14 Package Access 8.15 Software Reusability 8.16 Data Abstraction and Encapsulation 8.17 (Optional Case Study) Thinking About Objects: Starting to Program the Classes for the Elevator Simulation
Introduction
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
8.2 Implementing a Time Abstract Data Type with a Class
We introduce classes Time1 and TimeTest
Time1.java declares class Time1
TimeTest.java declares class TimeTest
public classes must be declared in separate files
Class Time1 will not execute by itself
Does not have method main
TimeTest, which has method main, creates (instantiates) and uses Time1 object
Time1.javaLine 5Time1 (subclass) extends superclass java.lang.Object Lines 6-8private variables Lines 12-15Time1 constructor then invokes method setTimeLine 19 public methods Lines 19-24Method setTime sets private variables according to arguments 1 // Fig. 8.1: Time1.java
2 // Time1 class declaration maintains the time in 24-hour format.
3 import java.text.DecimalFormat;
4
5 public class Time1 extends Object {
6 private int hour; // 0 - 23
7 private int minute; // 0 - 59
8 private int second; // 0 - 59
9
10 // Time1 constructor initializes each instance variable to zero;
11 // ensures that each Time1 object starts in a consistent state
12 public Time1()
13 {
14 setTime( 0, 0, 0 );
15 }
Time1 (subclass) extends superclass java.lang.Object (Chapter 9 discusses inheritance) private variables (and methods) are accessible only to methods in this class Method setTime sets private variables according to arguments public methods (and variables) are accessible wherever program has Time1 reference Time1 constructor creates Time1 object then invokes method setTime
Time1.java 26 // convert to String in universal-time format
27 public String toUniversalString()
28 {
29 DecimalFormat twoDigits = new DecimalFormat( "00" );
30
31 return twoDigits.format( hour ) + ":" +
32 twoDigits.format( minute ) + ":" + twoDigits.format( second );
33 }
34
35 // convert to String in standard-time format
36 public String toStandardString()
37 {
38 DecimalFormat twoDigits = new DecimalFormat( "00" );
39
40 return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" +
41 twoDigits.format( minute ) + ":" + twoDigits.format( second ) +
42 ( hour < 12 ? " AM" : " PM" );
43 }
44
45 } // end class Time1
8.2 Implementing a Time Abstract Data Type with a Class (cont.)
Every Java class must extend another class
Time1 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 Time1 constructor(lines 12-15)
TimeTest1.javaLine 9Declare and create instance of class Time1 by calling Time1 constructorLines 12-26 TimeTest1 interacts with Time1 by calling Time1 public methods 1 // Fig. 8.2: TimeTest1.java
2 // Class TimeTest1 to exercise class Time1.
3 import javax.swing.JOptionPane;
4
5 public class TimeTest1 {
6
7 public static void main( String args[] )
8 {
9 Time1 time = new Time1(); // calls Time1 constructor
10
11 // append String version of time to String output
12 String output = "The initial universal time is: " +
13 time.toUniversalString() + "\nThe initial standard time is: " +
14 time.toStandardString();
15
16 // change time and append updated time to output
17 time.setTime( 13, 27, 6 );
18 output += "\n\nUniversal time after setTime is: " +
19 time.toUniversalString() +
20 "\nStandard time after setTime is: " + time.
Declare and create instance of class Time1 by calling Time1 constructor TimeTest1 interacts with Time1 by calling Time1 public methods
TimeTest1.java 28 JOptionPane.showMessageDialog( null, output,
29 "Testing Class Time1", JOptionPane.INFORMATION_MESSAGE );
30
31 System.exit( 0 );
32
33 } // end main
34
35 } // end class TimeTest1
8.3 Class Scope
Class scope
Class variables and methods
Members are accessible to all class methods
Members can be referenced by name
objectReferenceName.objectMemberName
Shadowed (hidden) class variables
this.variableName
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
TimeTest2.javaLines 9-11Compiler error – TimeTest2 cannot directly access Time1’s private data 1 // Fig. 8.3: TimeTest2.java
2 // Errors resulting from attempts to access private members of Time1.
3 public class TimeTest2 {
4
5 public static void main( String args[] )
6 {
7 Time1 time = new Time1();
8
9 time.hour = 7; // error: hour is a private instance variable
10 time.minute = 15; // error: minute is a private instance variable
11 time.second = 30; // error: second is a private instance variable
12 }
13
14 } // end class TimeTest2
TimeTest2.java:9: hour has private access in Time1
time.hour = 7; // error: hour is a private instance variable
^
TimeTest2.java:10: minute has private access in Time1
time.minute = 15; // error: minute is a private instance variable
^
TimeTest2.java:11: second has private access in Time1
time.second = 30; // error: second is a private instance variable
^
3 errors
Compiler error – TimeTest2 cannot directly access Time1’s private data
8.5 Referring to the Current Object’s Members with this
Keyword this (this reference)
Allows an object to refers to itself
ThisTest.java 1 // Fig. 8.4: ThisTest.java
2 // Using the this reference to refer to instance variables and methods.
3 import javax.swing.*;
4 import java.text.DecimalFormat;
5
6 public class ThisTest {
7
8 public static void main( String args[] )
9 {
10 SimpleTime time = new SimpleTime( 12, 30, 19 );
11
12 JOptionPane.showMessageDialog( null, time.buildString(),
13 "Demonstrating the \"this\" Reference",
14 JOptionPane.INFORMATION_MESSAGE );
15
16 System.exit( 0 );
17 }
18
19 } // end class ThisTest
20
21 // class SimpleTime demonstrates the "this" reference
22 class SimpleTime {
23 private int hour;
24 private int minute;
25 private int second;
26
ThisTest.javaLines 31-33this used to distinguish between argumens and variables Lines 39-40use explicit and implicit this to call toStandarsString 27 // constructor uses parameter names identical to instance variable
28 // names; "this" reference required to distinguish between names
29 public SimpleTime( int hour, int minute, int second )
30 {
31 this.hour = hour; // set "this" object's hour
32 this.minute = minute; // set "this" object's minute
33 this.second = second; // set "this" object's second
34 }
35
36 // use explicit and implicit "this" to call toStandardString
37 public String buildString()
38 {
39 return "this.toStandardString(): " + this.toStandardString() +
40 "\ntoStandardString(): " + toStandardString();
41 }
42
43 // return String representation of SimpleTime
44 public String toStandardString()
45 {
46 DecimalFormat t
Use explicit and implicit this to call toStandardString this used to distinguish between arguments and ThisTest variables
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 ClassName( argument1, argument2, …, arugmentN );
new indicates that new object is created
ClassName indicates type of object created
arguments specifies constructor argument values
8.7 Using Overloaded Constructors
Overloaded constructors
Methods (in same class) may have same name
Must have different parameter lists
Time2.javaLines 12-15No-argument (default) constructor Line 14Use this to invoke the Time2 constructor declared at lines 30-33Lines 18-21Overloaded constructor has one int argument Lines 24-27Second overloaded constructor has two int arguments 1 // Fig. 8.5: Time2.java
2 // Time2 class declaration with overloaded constructors.
3 import java.text.DecimalFormat;
4
5 public class Time2 {
6 private int hour; // 0 - 23
7 private int minute; // 0 - 59
8 private int second; // 0 - 59
9
10 // Time2 constructor initializes each instance variable to zero;
11 // ensures that Time object starts in a consistent state
12 public Time2()
13 {
14 this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
15 }
No-argument (default) constructor Overloaded constructor has one int argument Second overloaded constructor has two int arguments Use this to invoke the Time2 constructor declared at lines 30-33
Time2.javaLines 30-33Third overloaded constructor has three int arguments Lines 36-40Fourth overloaded constructor has Time2 argument 29 // Time2 constructor: hour, minute and second supplied
30 public Time2( int h, int m, int s )
31 {
32 setTime( h, m, s ); // invoke setTime to validate time
33 }
34
35 // Time2 constructor: another Time2 object supplied
36 public Time2( Time2 time )
37 {
38 // invoke Time2 constructor with three arguments
39 this( time.hour, time.minute, time.second );
40 }
41
42 // set a new time value using universal time; perform
43 // validity checks on data; set invalid values to zero
44 public v
Fourth overloaded constructor has Time2 argument Third overloaded constructor has three int arguments
Time2.java 59
60 // convert to String in standard-time format
61 public String toStandardString()
62 {
63 DecimalFormat twoDigits = new DecimalFormat( "00" );
64
65 return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" +
66 twoDigits.format( minute ) + ":" + twoDigits.format( second ) +
67 ( hour < 12 ? " AM" : " PM" );
68 }
69
70 } // end class Time2
TimeTest3.java Lines 9-14Instantiate each Time2 reference using a different constructor 1 // Fig. 8.6: TimeTest3.java
2 // Overloaded constructors used to initialize Time2 objects.
3 import javax.swing.*;
4
5 public class TimeTest3 {
6
7 public static void main( String args[] )
8 {
9 Time2 t1 = new Time2(); // 00:00:00
10 Time2 t2 = new Time2( 2 ); // 02:00:00
11 Time2 t3 = new Time2( 21, 34 ); // 21:34:00
12 Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42
13 Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00
14 Time2 t6 = new Time2( t4 ); // 12:25:42
15
16 String output = "Constructed with: " +
17 "\nt1: all arguments defaulted" +
18 "\n " + t1.toUniversalString() +
19 "\n " + t1.toStandardString();
20
21 output += "\nt2: hour s
Instantiate each Time2 reference using a different constructor
Comments