انت هنا الان : شبكة جامعة بابل > موقع الكلية > نظام التعليم الالكتروني > مشاهدة المحاضرة

Introduction to classes and objects

Share |
الكلية كلية الهندسة/المسيب     القسم هندسة الطاقة     المرحلة 2
أستاذ المادة محمد علي محمد الشريفي       25/10/2012 07:48:11
1
1
8
classes and
objects: a deeper
look
2
outline
time1.java
(1 of 2)
1 // fig. 8.1: time1.java
2 // time1 class declaration maintains the time in 24-hour format.
3
4 public class time1
5 {
6 private int hour // 0 – 23
7 private int minute // 0 - 59
8 private int second // 0 - 59
9
10 // set a new time value using universal time ensure that
11 // the data remains consistent by setting invalid values to zero
12 public void settime( int h, int m, int s )
13
14 hour = ( ( h >= 0 && h < 24 ) ? h : 0 ) // validate hour
15 minute = ( ( m >= 0 && m < 60 ) ? m : 0 ) // validate minute
16 second = ( ( s >= 0 && s < 60 ) ? s : 0 ) // validate second
17 } // end method settime
18
private instance variables
declare public method settime
validate parameter values before setting
instance variables
2
3
outline
time1.java
(2 of 2)
19 // convert to string in universal-time format (hh:mm:ss)
20 public string touniversalstring()
21 {
22 return string.format( "%02d:%02d:%02d", hour, minute, second )
23 } // end method touniversalstring
24
25 // convert to string in standard-time format (h:mm:ss am or pm)
26 public string tostring()
27 {
28 return string.format( "%d:%02d:%02d %s",
29 ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
30 minute, second, ( hour < 12 ? "am" : "pm" ) )
31 } // end method tostring
32 } // end class time1
format strings
4
outline
time1test.java
(1 of 2)
1 // fig. 8.2: time1test.java
2 // time1 object used in an application.
3
4 public class time1test
5 {
6 public static void main( string args[] )
7 {
8 // create and initialize a time1 object
9 time1 time = new time1() // invokes time1 constructor
10
11 // output string representations of the time
12 system.out.print( "the initial universal time is: " )
13 system.out.println( time.touniversalstring() )
14 system.out.print( "the initial standard time is: " )
15 system.out.println( time.tostring() )
16 system.out.println() // output a blank line
17
create a time1 object
call touniversalstring method
call tostring method
3
5
outline
time1test.java
(2 of 2)
18 // change time and output updatingd time
19 time.settime( 13, 27, 6 )
20 system.out.print( "universal time after settime is: " )
21 system.out.println( time.touniversalstring() )
22 system.out.print( "standard time after settime is: " )
23 system.out.println( time.tostring() )
24 system.out.println() // output a blank line
25
26 // set time with invalid values output updatingd time
27 time.settime( 99, 99, 99 )
28 system.out.println( "after attempting invalid settings:" )
29 system.out.print( "universal time: " )
30 system.out.println( time.touniversalstring() )
31 system.out.print( "standard time: " )
32 system.out.println( time.tostring() )
33 } // end main
34 } // end class time1test
the initial universal time is: 00:00:00
the initial standard time is: 12:00:00 am
universal time after settime is: 13:27:06
standard time after settime is: 1:27:06 pm
after attempting invalid settings:
universal time: 00:00:00
standard time: 12:00:00 am
call settime method
call settime method
with invalid values
6
8.3 controlling access to members
• a class’s public interface
– public methods a view of the services the class provides
to the class’s clients
• a class’s implementation details
– private variables and private methods are not
accessible to the class’s clients
4
7 8.4 referring to the current object’s
members with the this reference
• the this reference
– any object can access a reference to itself with keyword
this
– non-static methods implicitly use this when referring
to the object’s instance variables and other methods
– can be used to access instance variables when they are
shadowed by local variables or method parameters
8
outline
thistest.java
(1 of 2)
1 // fig. 8.4: thistest.java
2 // this used implicitly and explicitly to refer to members of an object.
3
4 public class thistest
5 {
6 public static void main( string args[] )
7 {
8 simpletime time = new simpletime( 15, 30, 19 )
9 system.out.println( time.buildstring() )
10 } // end main
11 } // end class thistest
12
13 // class simpletime demonstrates the "this" reference
14 class simpletime
15 {
16 private int hour // 0-23
17 private int minute // 0-59
18 private int second // 0-59
19
20 // if the constructor uses parameter names identical to
21 // instance variable names the "this" reference is
22 // required to distinguish between names
23 public simpletime( int hour, int minute, int second )
24 {
25 this.hour = hour // set "this" object s hour
26 this.minute = minute // set "this" object s minute
27 this.second = second // set "this" object s second
28 } // end simpletime constructor
29
create new simpletime object
declare instance variables
method parameters shadow
instance variables
using this to access the object’s instance variables
5
9
outline
thistest.java
(2 of 2)
30 // use explicit and implicit "this" to call touniversalstring
31 public string buildstring()
32 {
33 return string.format( "%24s: %s\n%24s: %s",
34 "this.touniversalstring()", this.touniversalstring(),
35 "touniversalstring()", touniversalstring() )
36 } // end method buildstring
37
38 // convert to string in universal-time format (hh:mm:ss)
39 public string touniversalstring()
40 {
41 // "this" is not required here to access instance variables,
42 // because method does not have local variables with same
43 // names as instance variables
44 return string.format( "%02d:%02d:%02d",
45 this.hour, this.minute, this.second )
46 } // end method touniversalstring
47 } // end class simpletime
this.touniversalstring(): 15:30:19
touniversalstring(): 15:30:19
using this explicitly and implicitly
to call touniversalstring
use of this not necessary here
10
common programming error 8.2
it is often a logic error when a method contains a
parameter or local variable that has the same
name as a field of the class. in this case, use
reference this if you wish to access the field of
the class—otherwise, the method parameter or
local variable will be referenced.
6
11
error-prevention tip 8.1
avoid method parameter names or local variable
names that conflict with field names. this helps
prevent subtle, hard-to-locate bugs.
12 8.5 time class case study: overloaded
constructors
• overloaded constructors
– provide multiple constructor definitions with different
signatures
• no-argument constructor
– a constructor invoked without arguments
• the this reference can be used to invoke
another constructor
– allowed only as the first statement in a constructor’s body
7
13
outline
time2.java
(1 of 4)
1 // fig. 8.5: time2.java
2 // time2 class declaration with overloaded constructors.
3
4 public class time2
5 {
6 private int hour // 0 - 23
7 private int minute // 0 - 59
8 private int second // 0 - 59
9
10 // time2 no-argument constructor: initializes each instance variable
11 // to zero ensures that time2 objects start in a consistent state
12 public time2()
13 {
14 this( 0, 0, 0 ) // invoke time2 constructor with three arguments
15 } // end time2 no-argument constructor
16
17 // time2 constructor: hour supplied, minute and second defaulted to 0
18 public time2( int h )
19 {
20 this( h, 0, 0 ) // invoke time2 constructor with three arguments
21 } // end time2 one-argument constructor
22
23 // time2 constructor: hour and minute supplied, second defaulted to 0
24 public time2( int h, int m )
25 {
26 this( h, m, 0 ) // invoke time2 constructor with three arguments
27 } // end time2 two-argument constructor
28
no-argument constructor
invoke three-argument constructor
14
outline
time2.java
(2 of 4)
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 } // end time2 three-argument constructor
34
35 // time2 constructor: another time2 object supplied
36 public time2( time2 time )
37 {
38 // invoke time2 three-argument constructor
39 this( time.gethour(), time.getminute(), time.getsecond() )
40 } // end time2 constructor with a time2 object argument
41
42 // set methods
43 // set a new time value using universal time ensure that
44 // the data remains consistent by setting invalid values to zero
45 public void settime( int h, int m, int s )
46 {
47 sethour( h ) // set the hour
48 setminute( m ) // set the minute
49 setsecond( s ) // set the second
50 } // end method settime
51
call settime method
constructor takes a reference to another
time2 object as a parameter
could have directly accessed instance
variables of object time here
8
15
outline
time2.java
(3 of 4)
52 // validate and set hour
53 public void sethour( int h )
54 {
55 hour = ( ( h >= 0 && h < 24 ) ? h : 0 )
56 } // end method sethour
57
58 // validate and set minute
59 public void setminute( int m )
60 {
61 minute = ( ( m >= 0 && m < 60 ) ? m : 0 )
62 } // end method setminute
63
64 // validate and set second
65 public void setsecond( int s )
66 {
67 second = ( ( s >= 0 && s < 60 ) ? s : 0 )
68 } // end method setsecond
69
70 // get methods
71 // get hour value
72 public int gethour()
73 {
74 return hour
75 } // end method gethour
76
16
outline
time2.java
(4 of 4)
77 // get minute value
78 public int getminute()
79 {
80 return minute
81 } // end method getminute
82
83 // get second value
84 public int getsecond()
85 {
86 return second
87 } // end method getsecond
88
89 // convert to string in universal-time format (hh:mm:ss)
90 public string touniversalstring()
91 {
92 return string.format(
93 "%02d:%02d:%02d", gethour(), getminute(), getsecond() )
94 } // end method touniversalstring
95
96 // convert to string in standard-time format (h:mm:ss am or pm)
97 public string tostring()
98 {
99 return string.format( "%d:%02d:%02d %s",
100 ( (gethour() == 0 || gethour() == 12) ? 12 : gethour() % 12 ),
101 getminute(), getsecond(), ( gethour() < 12 ? "am" : "pm" ) )
102 } // end method tostring
103 } // end class time2
9
17
it is a syntax error when this is used in a
constructor’s body to call another constructor of
the same class if that call is not the first
statement in the constructor. it is also a syntax
error when a method attempts to invoke a
constructor directly via this.
common programming error 8.3
18 8.5 time class case study: overloaded
constructors (cont.)
• using set methods
– having constructors use set methods to modify instance
variables instead of modifying them directly simplifies
implementation changing
10
19
outline
time2test.java
(1 of 3)
1 // fig. 8.6: time2test.java
2 // overloaded constructors used to initialize time2 objects.
3
4 public class time2test
5 {
6 public static void main( string args[] )
7 {
8 time2 t1 = new time2() // 00:00:00
9 time2 t2 = new time2( 2 ) // 02:00:00
10 time2 t3 = new time2( 21, 34 ) // 21:34:00
11 time2 t4 = new time2( 12, 25, 42 ) // 12:25:42
12 time2 t5 = new time2( 27, 74, 99 ) // 00:00:00
13 time2 t6 = new time2( t4 ) // 12:25:42
14
15 system.out.println( "constructed with:" )
16 system.out.println( "t1: all arguments defaulted" )
17 system.out.printf( " %s\n", t1.touniversalstring() )
18 system.out.printf( " %s\n", t1.tostring() )
19
call overloaded constructors
20
outline
time2test.java
(2 of 3)
20 system.out.println(
21 "t2: hour specified minute and second defaulted" )
22 system.out.printf( " %s\n", t2.touniversalstring() )
23 system.out.printf( " %s\n", t2.tostring() )
24
25 system.out.println(
26 "t3: hour and minute specified second defaulted" )
27 system.out.printf( " %s\n", t3.touniversalstring() )
28 system.out.printf( " %s\n", t3.tostring() )
29
30 system.out.println( "t4: hour, minute and second specified" )
31 system.out.printf( " %s\n", t4.touniversalstring() )
32 system.out.printf( " %s\n", t4.tostring() )
33
34 system.out.println( "t5: all invalid values specified" )
35 system.out.printf( " %s\n", t5.touniversalstring() )
36 system.out.printf( " %s\n", t5.tostring() )
37
11
21
outline
time2test.java
(3 of 3)
38 system.out.println( "t6: time2 object t4 specified" )
39 system.out.printf( " %s\n", t6.touniversalstring() )
40 system.out.printf( " %s\n", t6.tostring() )
41 } // end main
42 } // end class time2test
t1: all arguments defaulted
00:00:00
12:00:00 am
t2: hour specified minute and second defaulted
02:00:00
2:00:00 am
t3: hour and minute specified second defaulted
21:34:00
9:34:00 pm
t4: hour, minute and second specified
12:25:42
12:25:42 pm
t5: all invalid values specified
00:00:00
12:00:00 am
t6: time2 object t4 specified
12:25:42
12:25:42 pm
22
8.8 composition
• composition
– a class can have references to objects of other classes as
members
– sometimes referred to as a has-a relationship
12
23
software engineering observation 8.9
one form of software reuse is composition, in
which a class has as members references to
objects of other classes.
24
outline
date.java
(1 of 3)
1 // fig. 8.7: date.java
2 // date class declaration.
3
4 public class date
5 {
6 private int month // 1-12
7 private int day // 1-31 based on month
8 private int year // any year
9
10 // constructor: call checkmonth to confirm proper value for month
11 // call checkday to confirm proper value for day
12 public date( int themonth, int theday, int theyear )
13 {
14 month = checkmonth( themonth ) // validate month
15 year = theyear // could validate year
16 day = checkday( theday ) // validate day
17
18 system.out.printf(
19 "date object constructor for date %s\n", this )
20 } // end date constructor
21
13
25
outline
date.java
(2 of 3)
22 // utility method to confirm proper month value
23 private int checkmonth( int testmonth )
24 {
25 if ( testmonth > 0 && testmonth <= 12 ) // validate month
26 return testmonth
27 else // month is invalid
28 {
29 system.out.printf(
30 "invalid month (%d) set to 1.", testmonth )
31 return 1 // maintain object in consistent state
32 } // end else
33 } // end method checkmonth
34
35 // utility method to confirm proper day value based on month and year
36 private int checkday( int testday )
37 {
38 int dayspermonth[] =
39 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
40
validates month value
validates day value
26
outline
date.java
(3 of 3)
41 // check if day in range for month
42 if ( testday > 0 && testday <= dayspermonth[ month ] )
43 return testday
44
45 // check for leap year
46 if ( month == 2 && testday == 29 && ( year % 400 == 0 ||
47 ( year % 4 == 0 && year % 100 != 0 ) ) )
48 return testday
49
50 system.out.printf( "invalid day (%d) set to 1.", testday )
51 return 1 // maintain object in consistent state
52 } // end method checkday
53
54 // return a string of the form month/day/year
55 public string tostring()
56 {
57 return string.format( "%d/%d/%d", month, day, year )
58 } // end method tostring
59 } // end class date
check if the day is
february 29 on a
leap year
14
27
outline
employee.java
1 // fig. 8.8: employee.java
2 // employee class with references to other objects.
3
4 public class employee
5 {
6 private string firstname
7 private string lastname
8 private date birthdate
9 private date hiredate
10
11 // constructor to initialize name, birth date and hire date
12 public employee( string first, string last, date dateofbirth,
13 date dateofhire )
14 {
15 firstname = first
16 lastname = last
17 birthdate = dateofbirth
18 hiredate = dateofhire
19 } // end employee constructor
20
21 // convert employee to string format
22 public string tostring()
23 {
24 return string.format( "%s, %s hired: %s birthday: %s",
25 lastname, firstname, hiredate, birthdate )
26 } // end method tostring
27 } // end class employee
employee contains references
to two date objects
implicit calls to hiredate and
birthdate’s tostring methods
28
outline
employeetest.java
1 // fig. 8.9: employeetest.java
2 // composition demonstration.
3
4 public class employeetest
5 {
6 public static void main( string args[] )
7 {
8 date birth = new date( 7, 24, 1949 )
9 date hire = new date( 3, 12, 1988 )
10 employee employee = new employee( "bob", "blue", birth, hire )
11
12 system.out.println( employee )
13 } // end main
14 } // end class employeetest
date object constructor for date 7/24/1949
date object constructor for date 3/12/1988
blue, bob hired: 3/12/1988 birthday: 7/24/1949
create an employee object
display the employee object

المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .
الرجوع الى لوحة التحكم