265
1 1992-2007 Pearson Education, Inc. All rights rese 8 Classes and Objects: A Deeper Look

1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

Embed Size (px)

Citation preview

Page 1: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

1

1992-2007 Pearson Education, Inc. All rights reserved.

8Classes and

Objects: A Deeper Look

Page 2: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

2

1992-2007 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn this chapter you will learn: Encapsulation and data hiding. The notions of data abstraction and abstract data types

(ADTs). To use keyword this. To use static variables and methods. To import static members of a class. To use the enum type to create sets of constants with

unique identifiers. How to declare enum constants with parameters.

Page 3: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

3

1992-2007 Pearson Education, Inc. All rights reserved.

8.1    Introduction8.2    Time Class Case Study8.3    Controlling Access to Members8.4    Referring to the Current Object’s

Members with the this Reference8.5    Time Class Case Study: Overloaded

Constructors8.6    Default and No-Argument

Constructors8.7    Notes on Set and Get Methods8.8    Composition8.9    Enumerations8.10   Garbage Collection and Method finalize

Page 4: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

4

1992-2007 Pearson Education, Inc. All rights reserved.

8.11    static Class Members8.12    static Import8.13    final Instance Variables8.14    Software Reusability8.15    Data Abstraction and Encapsulation8.16    Time Class Case Study: Creating Packages8.17    Package Access8.18    (Optional) GUI and Graphics Case

Study: Using Objects with Graphics8.19    (Optional) Software Engineering Case

Study: Starting to Program the Classes of the ATM System

8.20    Wrap-Up

Page 5: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

5

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study

•public services (or public interface)– public methods available for a client to use

• If a class does not define a constructor the compiler will provide a default constructor

• Instance variables– Can be initialized when they are declared or in a

constructor– Should maintain consistent (valid) values

Page 6: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

6

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.1

Methods that modify the values of private variables should verify that the intended new values are proper. If they are not, the set methods should place the private variables into an appropriate consistent state.

Page 7: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

7

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 8: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

8

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 9: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

9

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)public class Time1 {

privatint hour; // 0 – 23 private int minute; // 0 - 59 private int second; // 0 - 59

// set a new time value using universal time; ensure that public void setTime( int h, int m, int s ) {

}// convert to String in universal-time format (HH:MM:SS)

public String toUniversalString() { }

// convert to String in standard-time format (H:MM:SS AM or PM) public String toString()

{ }

} // end class Time1

Page 10: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

10

1992-2007 Pearson Education, Inc. All rights reserved.

• No constructor is provided• Three instnce variables

– Declared as private– Primitve types– Initilized to zero when creating a time1 objcet

• three methods– public void setTime()

• two of them display time in different formats– public String toUniversalString()– Public String toString()

Page 11: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

11

1992-2007 Pearson Education, Inc. All rights reserved.

• public void setTime(int h, int m, int s) {

hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour

minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute

second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second

} // end method setTimehour 0..23inute 0..59Second 0..59This is not a constructor shoud be invoked with a Time1 objcet

Page 12: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

12

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)// Fig. 8.1: Time1.java// Time1 class declaration maintains the time in 24-hour format.

public class Time1 {

privatint hour; // 0 – 23 private int minute; // 0 - 59 private int second; // 0 - 59

// set a new time value using universal time; ensure that // the data remains consistent by setting invalid values to zero

public void setTime( int h, int m, int s ) {

hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour

minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute

second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second

} // end method setTime

Page 13: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

13

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)// convert to String in universal-time format (HH:MM:SS)public String toUniversalString(){ return String.format( "%02d:%02d:%02d", hour, minute, second );} // end method toUniversalString

// convert to String in standard-time format (H:MM:SS AM or PM) public String toString()

{ return String.format( "%d:%02d:%02d %s", ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } // end method toString

} // end class Time1

Page 14: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

14

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)hour = (( h >= 0 && h < 24 ) ? h : 0 );is the ? Ternary operator in javaGeneral formCondition ? Expression1:expresion2;condition is a logical expresion

if the condition is true exprsion1 is evaluated else expresion2 is evaluatedEquivalent to if(condition) expresion1; else expresion2;

Page 15: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

15

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)hour = ( h >= 0 && h < 24 ) ? h : 0 );The right side of assignment reuturns either current value of h or 0 Depending on the truth value of h >= 0 && h < 24İf h is between 0..23 the expresion is true

Equivalent toİf(( h >= 0 && h < 24 )) hour = h;Else hour = 0:

Page 16: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

16

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)

•String method format– Similar to printf except it returns a formatted string

instead of displaying it in a command window•new implicitly invokes Time1’s default

constructor since Time1 does not declare any constructors

Page 17: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

17

1992-2007 Pearson Education, Inc. All rights reserved.

8.2  Time Class Case Study (Cont.)

•String method format– Similar to printf except it returns a formatted string

instead of displaying it in a command window– A static method without any string object

Page 18: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

18

1992-2007 Pearson Education, Inc. All rights reserved.

public String toUniversalString(){ return String.format( "%02d:%02d:%02d", hour, minute, second );} // end method toUniversalString

"%02d:%02d:%02d“ determinesThe format%02d an integer two digints

0 means if first is blank fill with 0s

Page 19: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

19

1992-2007 Pearson Education, Inc. All rights reserved.

This method can be written like that

public String toUniversalString(){ String s = String.format( "%02d:%02d:%02d", hour, minute, second );

return s;}

String.formant() returns a string which is assigned to String variable s

e.g.: if hour 2,munite 15 second 5S is “02:15:05”

Page 20: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

20

1992-2007 Pearson Education, Inc. All rights reserved.

public String toString(){ return String.format( "%d:%02d:%02d %s”, ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); }

"%d:%02d:%02d %s: ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) Second and third are just munite and second Forth is a stirng either AM or PM

Page 21: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

21

1992-2007 Pearson Education, Inc. All rights reserved.

First argument( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )İf hour is 0 or 12 12 is returnedelse hour mod 12 is returnedExampleTime:00:15:20 to 12:15:20 AM :05:15:20 to 5:15:20 AM as 5 % 12 = 5 :12:15:20 to 12:15:20 PM :21:15:20 to 9:15:20 PM as 21 % 12 = 9

Page 22: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

22

1992-2007 Pearson Education, Inc. All rights reserved.

toString

Can be used without refering the method namein a string expression the when the obcet name

appears immediately called to produce a string representation of the object

Page 23: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

23

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.2

Classes simplify programming, because the client can use only the public methods exposed by the class. Such methods are usually client oriented rather than implementation oriented. Clients are neither aware of, nor involved in, a class’s implementation. Clients generally care about what the class does but not how the class does it.

Page 24: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

24

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.3

Interfaces change less frequently than implementations. When an implementation changes, implementation-dependent code must change accordingly. Hiding the implementation reduces the possibility that other program parts will become dependent on class-implementation details.

Page 25: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

25

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 26: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

26

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Time1Test.java

(2 of 2)

18 // change time and output updated 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 updated 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

Page 27: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

27

1992-2007 Pearson Education, Inc. All rights reserved.

Test class for using Time1

Create Time1 objectsdefault constructor

00:00:00Set hour munite secondDisplay in universal and strandard formats

Page 28: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

28

1992-2007 Pearson Education, Inc. All rights reserved.

4 public class Time1Test 5 {6 public static void main( String args[] )7 {8 // create and initialize a Time1 object9 Time1 time = new Time1(); // invokes Time1 constructor1011 // output string representations of the time12 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 line17

Page 29: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

29

1992-2007 Pearson Education, Inc. All rights reserved.

18 // change time and output updated 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 line2526 // set time with invalid values; output updated 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 main34 } // end class Time1Test

Page 30: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

30

1992-2007 Pearson Education, Inc. All rights reserved.

The output

The initial universal time is: 00:00:00The initial standard time is: 12:00:00 AM

Universal time after setTime is: 13:27:06Standard time after setTime is: 1:27:06 PM

After attempting invalid settings:Universal time: 00:00:00Standard time: 12:00:00 AM

Page 31: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

31

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 32: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

32

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.1

An attempt by a method that is not a member of a class to access a private member of that class is a compilation error.

Page 33: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

33

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MemberAccessTest

.java

1 // Fig. 8.3: MemberAccessTest.java 2 // Private members of class Time1 are not accessible. 3 public class MemberAccessTest 4 { 5 public static void main( String args[] ) 6 { 7 Time1 time = new Time1(); // create and initialize Time1 object 8 9 time.hour = 7; // error: hour has private access in Time1 10 time.minute = 15; // error: minute has private access in Time1 11 time.second = 30; // error: second has private access in Time1 12 } // end main 13 } // end class MemberAccessTest MemberAccessTest.java:9: hour has private access in Time1 time.hour = 7; // error: hour has private access in Time1 ^ MemberAccessTest.java:10: minute has private access in Time1 time.minute = 15; // error: minute has private access in Time1 ^ MemberAccessTest.java:11: second has private access in Time1 time.second = 30; // error: second has private access in Time1 ^ 3 errors

Attempting to access private instance variables

Page 34: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

34

1992-2007 Pearson Education, Inc. All rights reserved.

8.4  Referring to the Current Object’s Members with the this Reference

3 public class MemberAccessTest 4 {5 public static void main( String args[] )6 {7 Time1 time = new Time1();

// create and initialize Time1 object89 time.hour = 7;// error: hour has private access in Time1 10 time.minute = 15;// error: minute has private access in Time111 time.second = 30;// error: second has private access in Time112 } // end main13 } // end class MemberAccessTest

Page 35: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

35

1992-2007 Pearson Education, Inc. All rights reserved.

output

MemberAccessTest.java:9: hour has private access in Time1 time.hour = 7; // error: hour has private access in Time1

^MemberAccessTest.java:10: minute has private access in Time1 time.minute = 15; // error: minute has private access in Time1

^MemberAccessTest.java:11: second has private access in Time1 time.second = 30; // error: second has private access in Time1

^3 errors

Page 36: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

36

1992-2007 Pearson Education, Inc. All rights reserved.

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

• A java file can contain more than one class– But only one class in each .java file can be public

Page 37: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

37

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 38: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

38

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 39: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

39

1992-2007 Pearson Education, Inc. All rights reserved.

8.4  Referring to the Current Object’s Members with the this Reference

1 // Fig. 8.4: ThisTest.java2 // this used implicitly and explicitly to refer to members of an object.34 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 main11 } // end class ThisTest

Page 40: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

40

1992-2007 Pearson Education, Inc. All rights reserved.

8.4  Referring to the Current Object’s Members with the this Reference

13 // class SimpleTime demonstrates the "this" reference14 class SimpleTime 15 {16 private int hour; // 0-2317 private int minute; // 0-5918 private int second; // 0-59 1920 // if the constructor uses parameter names identical to 21 // instance variable names the "this" reference is 22 // required to distinguish between names23 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 minute27 this.second = second; // set "this" object's second28 } // end SimpleTime constructor

Page 41: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

41

1992-2007 Pearson Education, Inc. All rights reserved.

8.4  Referring to the Current Object’s Members with the this Reference

30 // use explicit and implicit "this" to call toUniversalString31 public String buildString()32 {33 return String.format( "%24s: %s\n%24s: %s",

34 "this.toUniversalString()", this.toUniversalString(),

35 "toUniversalString()", toUniversalString() );

36 } // end method buildString37

Page 42: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

42

1992-2007 Pearson Education, Inc. All rights reserved.

Just the format string

Fife arguments "%24s: %s\n%24s: %s", four strings to be formated "this.toUniversalString()",

this.toUniversalString(), "toUniversalString()", toUniversalString()The output is:this.toUniversalString(): 15:30:19 toUniversalString(): 15:30:19

Page 43: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

43

1992-2007 Pearson Education, Inc. All rights reserved.

toUniversalString method

38 // convert to String in universal-time

format (HH:MM:SS)39 public String toUniversalString()40 { return String.format( "%02d:%02d:%02d", this.hour, this.minute, this.second );46 } // end method toUniversalString47 } // end class SimpleTime

Page 44: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

44

1992-2007 Pearson Education, Inc. All rights reserved.

this.toUniversalString(): 15:30:19 toUniversalString(): 15:30:19

Page 45: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

45

1992-2007 Pearson Education, Inc. All rights reserved.

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.

Page 46: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

46

1992-2007 Pearson Education, Inc. All rights reserved.

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.

Page 47: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

47

1992-2007 Pearson Education, Inc. All rights reserved.

Performance Tip 8.1

Java conserves storage by maintaining only one copy of each method per class—this method is invoked by every object of the class. Each object, on the other hand, has its own copy of the class’s instance variables (i.e., non-static fields). Each method of the class implicitly uses this to determine the specific object of the class to manipulate.

Page 48: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

48

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 49: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

49

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 50: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

50

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 51: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

51

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 52: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

52

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 53: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

53

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

• Class Time2 has – 5 constructors– 4 get and set methods – 2 display methods

Page 54: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

54

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

• Class Time2 has – 5 constructors

• Time2() // no argument constructor• Time2(int h) // set hour • Time2(int h, int m) // set hour and munite• Time2(int h, int m, int s) // set hour and munite and second• Time2(Time t) // takes a Time2 object

Page 55: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

55

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

• Class Time2 has – 4 get and set methods

• setTime(int h, int m, int s)• setHour(int h)• setMunite(int m)• setSecond(int s)

– display methods• toString()• toUniversalString()

Page 56: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

56

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

1 // Fig. 8.5: Time2.java2 // Time2 class declaration with overloaded constructors. 34 public class Time25 {6 private int hour; // 0 - 237 private int minute; // 0 - 598 private int second; // 0 - 59910 // 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

Page 57: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

57

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

17 // Time2 constructor: hour supplied, minute and second defaulted to 018 public Time2( int h ) 19 { 20 this( h, 0, 0 ); // invoke Time2 constructor with three arguments 21 } // end Time2 one-argument constructor 2223 // Time2 constructor: hour and minute supplied, second defaulted to 024 public Time2( int h, int m ) 25 { 26 this( h, m, 0 ); // invoke Time2 constructor with three arguments 27 } // end Time2 two-argument constructor

Page 58: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

58

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

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 time33 } // end Time2 three-argument constructor 3435 // 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

Page 59: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

59

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

42// Set Methods43// set a new time value using universal time; ensure that 44// the data remains consistent by setting invalid values to zero45 public void setTime( int h, int m, int s )46 {47 setHour( h ); // set the hour 48 setMinute( m ); // set the minute49 setSecond( s ); // set the second50 } // end method setTime

Page 60: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

60

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

52 // validate and set hour 53 public void setHour( int h ) 54 { 55 hour = ( ( h >= 0 && h < 24 ) ? h : 0 );56 } // end method setHour 5758 // validate and set minute 59 public void setMinute( int m ) 60 { 61 minute = ( ( m >= 0 && m < 60 ) ? m : 0 );62 } // end method setMinute 6364 // validate and set second65 public void setSecond( int s ) 66 { 67 second = ( ( s >= 0 && s < 60 ) ? s : 0 );68 } // end method setSecond

Page 61: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

61

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

70 // Get Methods 71 // get hour value 72 public int getHour() 73 { 74 return hour; 75 } // end method getHour77 // get minute value 78 public int getMinute() 79 { 80 return minute; 81 } // end method getMinute8283 // get second value 84 public int getSecond() 85 { 86 return second; 87 } // end method getSecond

Page 62: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

62

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

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 toString103 } // end class Time2

Page 63: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

63

1992-2007 Pearson Education, Inc. All rights reserved.

The format string is

"%d:%02d:%02d %s", // what to format three int one stringFirst int the hour( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),

// Second and third int: munite and secondgetMinute(),

getSecond(), // Forth a string either AM or PM ( getHour() < 12 ? "AM" : "PM"

Page 64: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

64

1992-2007 Pearson Education, Inc. All rights reserved.

8.5  Time Class Case Study: Overloaded Constructors

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

Page 65: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

65

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 66: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

66

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.4

A constructor can call methods of the class. Be aware that the instance variables might not yet be in a consistent state, because the constructor is in the process of initializing the object. Using instance variables before they have been initialized properly is a logic error.

Page 67: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

67

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.4

When one object of a class has a reference to another object of the same class, the first object can access all the second object’s data and methods (including those that are private).

Page 68: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

68

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 69: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

69

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.5

When implementing a method of a class, use the class’s set and get methods to access the class’s private data. This simplifies code maintenance and reduces the likelihood of errors.

Page 70: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

70

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 71: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

71

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 72: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

72

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 73: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

73

1992-2007 Pearson Education, Inc. All rights reserved.

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

11 t1.setTime( 12, 25, 42 ); // 12:25:42// these methods to the Time2 class

11 t3.setTime( 6, 11,0); // 06:11:00

11 t5.setTime(11,0,0); // 11:00:00

Page 74: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

74

1992-2007 Pearson Education, Inc. All rights reserved.

Examples of printsSystem.out.println( "Constructed with:" );System.out.println( "t1: all arguments defaulted" );System.out.printf( " %s\n",t1.toUniversalString() );System.out.printf( " %s\n", t1.toString() ); using the toStrig and toUniversalString methods

Page 75: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

75

1992-2007 Pearson Education, Inc. All rights reserved.

8.6  Default and No-Argument Constructors

• Every class must have at least one constructor– If no constructors are declared, the compiler will create a

default constructor• Takes no arguments and initializes instance variables to their

initial values specified in their declaration or to their default values

– Default values are zero for primitive numeric types, false for boolean values and null for references

– If constructors are declared, the default initialization for objects of the class will be performed by a no-argument constructor (if one is declared)

Page 76: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

76

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.5

5If a class has constructors, but none of the public constructors are no-argument constructors, and a program attempts to call a no-argument constructor to initialize an object of the class, a compilation error occurs. A constructor can be called with no arguments only if the class does not have any constructors (in which case the default constructor is called) or if the class has a public no-argument constructor.

Page 77: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

77

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.6

6Java allows other methods of the class besides its constructors to have the same name as the class and to specify return types. Such methods are not constructors and will not be called when an object of the class is instantiated. Java determines which methods are constructors by locating the methods that have the same name as the class and do not specify a return type.

Page 78: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

78

1992-2007 Pearson Education, Inc. All rights reserved.

8.7  Notes on Set and Get Methods

• Set methods– Also known as mutator methods– Assign values to instance variables– Should validate new values for instance variables

• Can return a value to indicate invalid data

• Get methods– Also known as accessor methods or query methods– Obtain the values of instance variables– Can control the format of the data it returns

Page 79: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

79

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.7

When necessary, provide public methods to change and retrieve the values of private instance variables. This architecture helps hide the implementation of a class from its clients, which improves program modifiability.

Page 80: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

80

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.8

Class designers need not provide set or get methods for each private field. These capabilities should be provided only when it makes sense.

Page 81: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

81

1992-2007 Pearson Education, Inc. All rights reserved.

8.7  Notes on Set and Get Methods (Cont.)

• Predicate methods– Test whether a certain condition on the object is true or

false and returns the result– Example: an isEmpty method for a container class (a

class capable of holding many objects)

• Encapsulating specific tasks into their own methods simplifies debugging efforts

Page 82: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

82

1992-2007 Pearson Education, Inc. All rights reserved.

Other class examples

• A product class– Variables:

• Name of product• Code of product• Sale price, purchase price• Amout in stock

– Behavior• Define a new product• Give a code to the product• Order product• Sell product• Display stock or prices• Chage selling or ordering prices

Page 83: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

83

1992-2007 Pearson Education, Inc. All rights reserved.

Other class examples

• Note that– When ordering products stock should increase– When selling products stock shold decrease

• A store class may create products– Use the product class to do many operations related to

sales

Page 84: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

84

1992-2007 Pearson Education, Inc. All rights reserved.

8.8  Composition

• Composition– A class can have references to objects of other classes as

members– Sometimes referred to as a has-a relationship

Page 85: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

85

1992-2007 Pearson Education, Inc. All rights reserved.

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.

Page 86: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

86

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 87: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

87

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 88: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

88

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 89: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

89

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 90: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

90

1992-2007 Pearson Education, Inc. All rights reserved.

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

Page 91: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

91

1992-2007 Pearson Education, Inc. All rights reserved.

• Employee class– atributes

• name,lastname : String• hire and birth dates : a Date object

• A Date object• day, month, year• A constructor and• checkMonth and checkDay methods

– Check if month is 1..12 – Day is 1.. Proper for a month considering leap years

• toString method

Page 92: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

92

1992-2007 Pearson Education, Inc. All rights reserved.

1 // Fig. 8.9: EmployeeTest.java2 // Composition demonstration.34 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 );1112 System.out.println( employee );13 } // end main14 } // end class EmployeeTest

Page 93: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

93

1992-2007 Pearson Education, Inc. All rights reserved.

outputDate object constructor for date 7/24/1949Date object constructor for date 3/12/1988Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949

Page 94: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

94

1992-2007 Pearson Education, Inc. All rights reserved.

4 public class Date 5 {6 private int month; // 1-127 private int day; // 1-31 based on month8 private int year; // any year910 // constructor: call checkMonth to confirm proper value for month; 11 // call checkDay to confirm proper value for day12 public Date( int theMonth, int theDay, int theYear )13 {14 month = checkMonth( theMonth ); // validate month15 year = theYear; // could validate year16 day = checkDay( theDay ); // validate day1718 System.out.printf( 19 "Date object constructor for date %s\n", this );20 } // end Date constructor

Page 95: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

95

1992-2007 Pearson Education, Inc. All rights reserved.

22 // utility method to confirm proper month value

23 private int checkMonth( int testMonth )24 {25 if ( testMonth > 0 && testMonth <= 12 )

// validate month26 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 state32 } // end else33 } // end method checkMonth

Page 96: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

96

1992-2007 Pearson Education, Inc. All rights reserved.

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 };4041 // check if day in range for month42 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )43 return testDay;44 45 // check for leap year46 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 state52 } // end method checkDay

Page 97: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

97

1992-2007 Pearson Education, Inc. All rights reserved.

54 // return a String of the form month/day/year55 public String toString()56 { 57 return String.format(

"%d/%d/%d", month, day, year ); 58 } // end method toString59 } // end class Date

Page 98: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

98

1992-2007 Pearson Education, Inc. All rights reserved.

4 public class Employee 5 {6 private String firstName;7 private String lastName;8 private Date birthDate;9 private Date hireDate; 1011 // constructor to initialize name, birth date and hire date12 public Employee( String first, String last,

Date dateOfBirth, Date dateOfHire )

14 {15 firstName = first;16 lastName = last;17 birthDate = dateOfBirth;18 hireDate = dateOfHire;19 } // end Employee constructor

Page 99: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

99

1992-2007 Pearson Education, Inc. All rights reserved.

21 // convert Employee to String format22 public String toString()23 {24 return String.format( "%s, %s Hired: %s

Birthday: %s", 25 lastName, firstName, hireDate, birthDate );26 } // end method toString27 } // end class Employee

Page 100: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

100

1992-2007 Pearson Education, Inc. All rights reserved.

8.9  Enumerations

•enum types– Declared with an enum declaration

• A comma-separated list of enum constants• Declares an enum class with the following restrictions:

– enum types are implicitly final– enum constants are implicitly static– Attempting to create an object of an enum type with new is a compilation error

– enum constants can be used anywhere constants can– enum constructor

• Like class constructors, can specify parameters and be overloaded

Page 101: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

101

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Book.java

(1 of 2)

1 // Fig. 8.10: Book.java 2 // Declaring an enum type with constructor and explicit instance fields 3 // and accessors for these field 4 5 public enum Book 6 { 7 // declare constants of enum type 8 JHTP6( "Java How to Program 6e", "2005" ), 9 CHTP4( "C How to Program 4e", "2004" ), 10 IW3HTP3( "Internet & World Wide Web How to Program 3e", "2004" ), 11 CPPHTP4( "C++ How to Program 4e", "2003" ), 12 VBHTP2( "Visual Basic .NET How to Program 2e", "2002" ), 13 CSHARPHTP( "C# How to Program", "2002" ); 14 15 // instance fields 16 private final String title; // book title 17 private final String copyrightYear; // copyright year 18 19 // enum constructor 20 Book( String bookTitle, String year ) 21 { 22 title = bookTitle; 23 copyrightYear = year; 24 } // end enum Book constructor 25

Declare six enum constants

Arguments to pass to the enum constructor

Declare enum constructor Book

Declare instance variables

Page 102: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

102

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Book.java

(2 of 2)

26 // accessor for field title

27 public String getTitle()

28 {

29 return title;

30 } // end method getTitle

31

32 // accessor for field copyrightYear

33 public String getCopyrightYear()

34 {

35 return copyrightYear;

36 } // end method getCopyrightYear

37 } // end enum Book

Page 103: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

103

1992-2007 Pearson Education, Inc. All rights reserved.

8.9  Enumerations (Cont.)

•static method values– Generated by the compiler for every enum– Returns an array of the enum’s constants in the order in

which they were declared•static method range of class EnumSet

– Takes two parameters, the first and last enum constants in the desired range

– Returns an EnumSet containing the constants in that range, inclusive

– An enhanced for statement can iterate over an EnumSet as it can over an array

Page 104: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

104

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

EnumTest.java

(1 of 2)

1 // Fig. 8.11: EnumTest.java 2 // Testing enum type Book. 3 import java.util.EnumSet; 4 5 public class EnumTest 6 { 7 public static void main( String args[] ) 8 { 9 System.out.println( "All books:\n" ); 10 11 // print all books in enum Book 12 for ( Book book : Book.values() ) 13 System.out.printf( "%-10s%-45s%s\n", book, 14 book.getTitle(), book.getCopyrightYear() ); 15 16 System.out.println( "\nDisplay a range of enum constants:\n" ); 17 18 // print first four books 19 for ( Book book : EnumSet.range( Book.JHTP6, Book.CPPHTP4 ) ) 20 System.out.printf( "%-10s%-45s%s\n", book, 21 book.getTitle(), book.getCopyrightYear() ); 22 } // end main 23 } // end class EnumTest

Enhanced for loop iterates for each enum constant in the array returned by method value

Enhanced for loop iterates for each enum constant in the EnumSet returned by method range

Page 105: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

105

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

EnumTest.java

(2 of 2)

All books: JHTP6 Java How to Program 6e 2005 CHTP4 C How to Program 4e 2004 IW3HTP3 Internet & World Wide Web How to Program 3e 2004 CPPHTP4 C++ How to Program 4e 2003 VBHTP2 Visual Basic .NET How to Program 2e 2002 CSHARPHTP C# How to Program 2002 Display a range of enum constants: JHTP6 Java How to Program 6e 2005 CHTP4 C How to Program 4e 2004 IW3HTP3 Internet & World Wide Web How to Program 3e 2004 CPPHTP4 C++ How to Program 4e 2003

Page 106: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

106

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.6

In an enum declaration, it is a syntax error to declare enum constants after the enum type’s constructors, fields and methods in the enum declaration.

Page 107: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

107

1992-2007 Pearson Education, Inc. All rights reserved.

8.10  Garbage Collection and Method finalize

• Garbage collection– JVM marks an object for garbage collection when there

are no more references to that object– JVM’s garbage collector will retrieve those objects memory

so it can be used for other objects•finalize method

– All classes in Java have the finalize method• Inherited from the Object class

– finalize is called by the garbage collector when it performs termination housekeeping

– finalize takes no parameters and has return type void

Page 108: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

108

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.10

A class that uses system resources, such as files on disk, should provide a method to eventually release the resources. Many Java API classes provide close or dispose methods for this purpose. For example, class Scanner (java.sun.com/javase/6/docs/api/java/util/Scanner.html) has a close method.

Page 109: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

109

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members

•static fields– Also known as class variables– Represents class-wide information– Used when:

• all objects of the class should share the same copy of this instance variable or

• this instance variable should be accessible even when no objects of the class exist

– Can be accessed with the class name or an object name and a dot (.)

– Must be initialized in their declarations, or else the compiler will initialize it with a default value (0 for ints)

Page 110: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

110

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.11

Use a static variable when all objects of a class must use the same copy of the variable.

Page 111: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

111

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.12

Static class variables and methods exist, and can be used, even if no objects of that class have been instantiated.

Page 112: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

112

1992-2007 Pearson Education, Inc. All rights reserved.

Good Programming Practice 8.1

Invoke every static method by using the class name and a dot (.) to emphasize that the method being called is a static method.

Page 113: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

113

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Employee.java

(1 of 2)

1 // Fig. 8.12: Employee.java

2 // Static variable used to maintain a count of the number of

3 // Employee objects in memory.

4

5 public class Employee

6 {

7 private String firstName;

8 private String lastName;

9 private static int count = 0; // number of objects in memory

10

11 // initialize employee, add 1 to static count and

12 // output String indicating that constructor was called

13 public Employee( String first, String last )

14 {

15 firstName = first;

16 lastName = last;

17

18 count++; // increment static count of employees

19 System.out.printf( "Employee constructor: %s %s; count = %d\n",

20 firstName, lastName, count );

21 } // end Employee constructor 22

Declare a static field

Increment static field

Page 114: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

114

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Employee.java

(2 of 2)

23 // subtract 1 from static count when garbage 24 // collector calls finalize to clean up object; 25 // confirm that finalize was called 26 protected void finalize() 27 { 28 count--; // decrement static count of employees 29 System.out.printf( "Employee finalizer: %s %s; count = %d\n", 30 firstName, lastName, count ); 31 } // end method finalize 32 33 // get first name 34 public String getFirstName() 35 { 36 return firstName; 37 } // end method getFirstName 38 39 // get last name 40 public String getLastName() 41 { 42 return lastName; 43 } // end method getLastName 44 45 // static method to get static count value 46 public static int getCount() 47 { 48 return count; 49 } // end method getCount 50 } // end class Employee

Declare method finalize

Declare static method getCount to get static field count

Page 115: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

115

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

EmployeeTest.java

(1 of 3)

1 // Fig. 8.13: EmployeeTest.java 2 // Static member demonstration. 3 4 public class EmployeeTest 5 { 6 public static void main( String args[] ) 7 { 8 // show that count is 0 before creating Employees 9 System.out.printf( "Employees before instantiation: %d\n", 10 Employee.getCount() ); 11 12 // create two Employees; count should be 2 13 Employee e1 = new Employee( "Susan", "Baker" ); 14 Employee e2 = new Employee( "Bob", "Blue" ); 15

Call static method getCount using class name Employee

Create new Employee objects

Page 116: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

116

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

EmployeeTest.java

(2 of 3)

16 // show that count is 2 after creating two Employees

17 System.out.println( "\nEmployees after instantiation: " );

18 System.out.printf( "via e1.getCount(): %d\n", e1.getCount() );

19 System.out.printf( "via e2.getCount(): %d\n", e2.getCount() );

20 System.out.printf( "via Employee.getCount(): %d\n",

21 Employee.getCount() );

22

23 // get names of Employees

24 System.out.printf( "\nEmployee 1: %s %s\nEmployee 2: %s %s\n\n",

25 e1.getFirstName(), e1.getLastName(),

26 e2.getFirstName(), e2.getLastName() );

27

28 // in this example, there is only one reference to each Employee,

29 // so the following two statements cause the JVM to mark each

30 // Employee object for garbage collection

31 e1 = null;

32 e2 = null;

33

34 System.gc(); // ask for garbage collection to occur now 35

Call static method getCount using variable name

Call static method getCount using class name

Remove references to objects, JVM will mark them for garbage collection

Call static method gc of class System to indicate that garbage collection should be attempted

Page 117: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

117

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

EmployeeTest.java

(3 of 3)

36 // show Employee count after calling garbage collector; count

37 // displayed may be 0, 1 or 2 based on whether garbage collector

38 // executes immediately and number of Employee objects collected

39 System.out.printf( "\nEmployees after System.gc(): %d\n",

40 Employee.getCount() );

41 } // end main

42 } // end class EmployeeTest Employees before instantiation: 0 Employee constructor: Susan Baker; count = 1 Employee constructor: Bob Blue; count = 2 Employees after instantiation: via e1.getCount(): 2 via e2.getCount(): 2 via Employee.getCount(): 2 Employee 1: Susan Baker Employee 2: Bob Blue Employee finalizer: Bob Blue; count = 1 Employee finalizer: Susan Baker; count = 0 Employees after System.gc(): 0

Call static method getCount

Page 118: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

118

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)

• The employee class has– two instance variables

• firstname,lastname– one static variable to count the employees

• count : to count number of employees– A constructor

• Taking firstname and lastname• İncrementing counter by one when creating a new employee

– A finalize method• Decrementing counter by one when distrcuting an employee

object– get method for first and last name– A static get method for counter

Page 119: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

119

1992-2007 Pearson Education, Inc. All rights reserved.

What main does

Get counter of Employee classstatic method without any objcet

Generate two employeescall getCounter on each employee and

with using class namePritnt employee information

first last names of the two employeesAssing the two ref variabe to null e1 = null; e2 = null; no more reference to employee objectsAsk garbage collector to distroy objcets in memoryPrint count – number of employees after garbage collector

Page 120: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

120

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)4 public class EmployeeTest 5 {6 public static void main( String args[] )7 {8 // show that count is 0 before creating Employees9 System.out.printf( "Employees before instantiation:

%d\n", Employee.getCount() );1112 // create two Employees; count should be 213 Employee e1 = new Employee( "Susan", "Baker" );14 Employee e2 = new Employee( "Bob", "Blue" );16 // show that count is 2 after creating two Employees17 System.out.println( "\nEmployees after instantiation: " );18 System.out.printf( "via e1.getCount(): %d\n",

e1.getCount() );19 System.out.printf( "via e2.getCount(): %d\n",

e2.getCount() );20 System.out.printf( "via Employee.getCount(): %d\n", 21 Employee.getCount() );

Page 121: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

121

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)23 // get names of Employees24 System.out.printf( "\nEmployee 1: %s %s\nEmployee 2: %s %s\n\n",25 e1.getFirstName(), e1.getLastName(), 26 e2.getFirstName(), e2.getLastName() );27// in this example, there is only one reference to each Employee,// so the following two statements cause the JVM to mark each // Employee object for garbage collection 31 e1 = null; 32 e2 = null; 3334 System.gc();

// ask for garbage collection to occur now

Page 122: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

122

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)36 // show Employee count after calling garbage collector; count 37 // displayed may be 0, 1 or 2 based on whether garbage collector38 // executes immediately and number of Employee objects collected39 System.out.printf( "\nEmployees after System.gc(): %d\n", 40 Employee.getCount() );41 } // end main42 } // end class EmployeeTest

Page 123: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

123

1992-2007 Pearson Education, Inc. All rights reserved.

outputEmployees before instantiation: 0Employee constructor: Susan Baker; count = 1Employee constructor: Bob Blue; count = 2

Employees after instantiation:via e1.getCount(): 2via e2.getCount(): 2via Employee.getCount(): 2

Employee 1: Susan BakerEmployee 2: Bob Blue

Employee finalizer: Bob Blue; count = 1Employee finalizer: Susan Baker; count = 0

Employees after System.gc(): 0

Page 124: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

124

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)5 public class Employee 6 {7 private String firstName;8 private String lastName;9 private static int count = 0; // number of objects in memory1011 // initialize employee, add 1 to static count and 12 // output String indicating that constructor was called13 public Employee( String first, String last )14 {15 firstName = first;16 lastName = last;1718 count++; // increment static count of employees19 System.out.printf( "Employee constructor: %s %s; count = %d”,20 firstName, lastName, count );21 } // end Employee constructor

Page 125: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

125

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)23 // subtract 1 from static count when garbage 24 // collector calls finalize to clean up object;25 // confirm that finalize was called26 protected void finalize()27 {28 count--; // decrement static count of employees29 System.out.printf( "Employee finalizer: %s %s; count = %d\n",30 firstName, lastName, count );31 } // end method finalize32

Page 126: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

126

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.) 33 // get first name

34 public String getFirstName() 35 { 36 return firstName; 37 } // end method getFirstName

39 // get last name40 public String getLastName() 41 { 42 return lastName; 43 } // end method getLastName4445 // static method to get static count value46 public static int getCount() 47 { 48 return count; 49 } // end method getCount 50 } // end class Employee

Page 127: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

127

1992-2007 Pearson Education, Inc. All rights reserved.

8.11  static Class Members (Cont.)

•String objects are immutable– String concatenation operations actually result in the

creation of a new String object•static method gc of class System

– Indicates that the garbage collector should make a best-effort attempt to reclaim objects eligible for garbage collection

– It is possible that no objects or only a subset of eligible objects will be collected

•static methods cannot access non-static class members

– Also cannot use the this reference

Page 128: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

128

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.7

A compilation error occurs if a static method calls an instance (non-static) method in the same class by using only the method name. Similarly, a compilation error occurs if a static method attempts to access an instance variable in the same class by using only the variable name.

Page 129: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

129

1992-2007 Pearson Education, Inc. All rights reserved.

Referring to this in a static method is a syntax error.

Common Programming Error 8.8

Page 130: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

130

1992-2007 Pearson Education, Inc. All rights reserved.

8.12  static Import

•static import declarations– Enables programmers to refer to imported static

members as if they were declared in the class that uses them

– Single static import• import static packageName.ClassName.staticMemberName;

– static import on demand• import static packageName.ClassName.*;• Imports all static members of the specified class

Page 131: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

131

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

StaticImportTest

.java

1 // Fig. 8.14: StaticImportTest.java

2 // Using static import to import static methods of class Math.

3 import static java.lang.Math.*;

4

5 public class StaticImportTest

6 {

7 public static void main( String args[] )

8 {

9 System.out.printf( "sqrt( 900.0 ) = %.1f\n", sqrt( 900.0 ) );

10 System.out.printf( "ceil( -9.8 ) = %.1f\n", ceil( -9.8 ) );

11 System.out.printf( "log( E ) = %.1f\n", log( E ) );

12 System.out.printf( "cos( 0.0 ) = %.1f\n", cos( 0.0 ) );

13 } // end main

14 } // end class StaticImportTest sqrt( 900.0 ) = 30.0 ceil( -9.8 ) = -9.0 log( E ) = 1.0 cos( 0.0 ) = 1.0

static import on demand

Use Math’s static methods and instance variable without preceding them with Math.

Page 132: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

132

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.9

A compilation error occurs if a program attempts to import static methods that have the same signature or static fields that have the same name from two or more classes.

Page 133: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

133

1992-2007 Pearson Education, Inc. All rights reserved.

8.13  final Instance Variables

• Principle of least privilege– Code should have only the privilege and access it needs to

accomplish its task, but no more•final instance variables

– Keyword final• Specifies that a variable is not modifiable (is a constant)

– final instance variables can be initialized at their declaration

• If they are not initialized in their declarations, they must be initialized in all constructors

Page 134: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

134

1992-2007 Pearson Education, Inc. All rights reserved.

Declaring an instance variable as final helps enforce the principle of least privilege. If an instance variable should not be modified, declare it to be final to prevent modification.

Software Engineering Observation 8.13

Page 135: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

135

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Increment.java

1 // Fig. 8.15: Increment.java 2 // final instance variable in a class. 3 4 public class Increment 5 { 6 private int total = 0; // total of all increments 7 private final int INCREMENT; // constant variable (uninitialized) 8 9 // constructor initializes final instance variable INCREMENT 10 public Increment( int incrementValue ) 11 { 12 INCREMENT = incrementValue; // initialize constant variable (once) 13 } // end Increment constructor 14 15 // add INCREMENT to total 16 public void addIncrementToTotal() 17 { 18 total += INCREMENT; 19 } // end method addIncrementToTotal 20 21 // return String representation of an Increment object's data 22 public String toString() 23 { 24 return String.format( "total = %d", total ); 25 } // end method toIncrementString 26 } // end class Increment

Declare final instance variable

Initialize final instance variable inside a constructor

Page 136: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

136

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

IncrementTest.java

1 // Fig. 8.16: IncrementTest.java 2 // final variable initialized with a constructor argument. 3 4 public class IncrementTest 5 { 6 public static void main( String args[] ) 7 { 8 Increment value = new Increment( 5 ); 9 10 System.out.printf( "Before incrementing: %s\n\n", value ); 11 12 for ( int i = 1; i <= 3; i++ ) 13 { 14 value.addIncrementToTotal(); 15 System.out.printf( "After increment %d: %s\n", i, value ); 16 } // end for 17 } // end main 18 } // end class IncrementTest Before incrementing: total = 0 After increment 1: total = 5 After increment 2: total = 10 After increment 3: total = 15

Create an Increment object

Call method addIncrementToTotal

Page 137: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

137

1992-2007 Pearson Education, Inc. All rights reserved.

Attempting to modify a final instance variable after it is initialized is a compilation error.

Common Programming Error 8.10

Page 138: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

138

1992-2007 Pearson Education, Inc. All rights reserved.

Attempts to modify a final instance variable are caught at compilation time rather than causing execution-time errors. It is always preferable to get bugs out at compilation time, if possible, rather than allow them to slip through to execution time (where studies have found that the cost of repair is often many times more expensive).

Error-Prevention Tip 8.2

Page 139: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

139

1992-2007 Pearson Education, Inc. All rights reserved.

A final field should also be declared static if it is initialized in its declaration. Once a final field is initialized in its declaration, its value can never change. Therefore, it is not necessary to have a separate copy of the field for every object of the class. Making the field static enables all objects of the class to share the final field.

Software Engineering Observation 8.14

Page 140: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

140

1992-2007 Pearson Education, Inc. All rights reserved.

Not initializing a final instance variable in its declaration or in every constructor of the class yields a compilation error indicating that the variable might not have been initialized. The same error occurs if the class initializes the variable in some, but not all, of the class’s constructors.

Common Programming Error 8.11

Page 141: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

141

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Increment.java

Increment.java:13: variable INCREMENT might not have been initialized } // end Increment constructor ^ 1 error

Page 142: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

142

1992-2007 Pearson Education, Inc. All rights reserved.

Examples – The quiz question Spring 2008

• A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24 hour period is $10.00 Assume that no car parks for longer than 24 hours at a time (parking periods can not exceed a day). Write a java program that will calculate and print the parking charges for a car.

Page 143: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

143

1992-2007 Pearson Education, Inc. All rights reserved.

Examples – The quiz questions• Enterance and leaving times are taken as hour and minute• Create a Time classs with appropriate instance variables (do not consider

seconds)• Add a two parameter constructor(do not check the consistency of hour and

minute)• Add a method to the Time class totalMinutes to calculate total number of

minutes since midnight• Add a non-static mehod to the Time class invoked on a Time object, and

accepting another Time object as a parameter to calculate and return number of hours between the two time objects

• Do not include any get, set or display method for simplicity • Create a test class to provide the enterance and leaving times of a car (you

need not get them from the user as input)• Add a method to the test class to compute the parking charge for a car• Display the charge to the command window

Page 144: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

144

1992-2007 Pearson Education, Inc. All rights reserved.

Examples – The quiz questionpublic class Time { private int hour; private int minute; public Time(int h, int m) { hour = h; minute = m; } public int totalMinutes() { return 60*hour + minute; } public int hourDifference(Time t) { return ( toMinute() – t.toMinute() ) / 60 +1; }}

Page 145: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

145

1992-2007 Pearson Education, Inc. All rights reserved.

Examples – The quiz questionpublic class TimeTest { public static void main(String args[]) { Time enter = new Time(10,20); Time leave = new Time(18,35); int wholeHours = leave.hourDifference(enter); double amount = payment(wholeHours); System.out.println(“total payment: “+ amount); } public static double payment(int h) { if(h < 4) return 3.0; double pay = 3.0 + 0.5*(h-3); if(pay < 10.0) return pay; else return 10.0; }}

Page 146: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

146

1992-2007 Pearson Education, Inc. All rights reserved.

Example Bank Accounts• Account example revisited• People can open accounts in a bank• Account has

– Attributes: • Personal information (a Person class)• Initial balance• On which bank

– Actions: • Deposit money• Withdraw money• get balance• Transfer money from one account to another

– Different commusion rates are applied whether the accounts are on the same bank or not

Page 147: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

147

1992-2007 Pearson Education, Inc. All rights reserved.

Example Bank Accounts (cont.)

• Banks can– Earn commusions from transfer of money – Accumulate balances– Get total balnce of a bank– Get total transfer revenue of a bank– Total number of accounts opened in a bank

• When a new account is opened on a bank total number of accouts is incremented by one and

• The accout number is automatically genertated by assigning this number as the new accounts number

Page 148: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

148

1992-2007 Pearson Education, Inc. All rights reserved.

Example Bank Accounts (cont.)• Actions

– Open account– Doposit money– Withdraw money– Transfer money

• Involved parties are - actors– People, bank accounts , banks

• Relationships between actors– Persons has bank accouts– Bank accounts has money in it– Bank accounts are opend in banks – each bank account has a

bank• Has a relationship betwee two objects

Page 149: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

149

1992-2007 Pearson Education, Inc. All rights reserved.

Example Bank Accounts (cont.)

• One of the questions is:• Where to implement the methods say

– Withdraw monney is a method of bank accounts , banks or persons

• People themself withdraw money – action of people• Money is withdrawn from bank accounts• Money is withdrawn from banks as well

• In procedural programming withdraw ation is implemented by a function (C function) taking parameters – bank, account, money, username …

Page 150: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

150

1992-2007 Pearson Education, Inc. All rights reserved.

Example Bank Accounts (cont.)• In the test class TestBank

– Create new banks• yKredi, aBank

– Create new persons• ali, veli ,ayşe

– These persons can open accounts by depositning an initial amount on a specified bank

• Ali by 1000 in yKredi• Veri by 500 in yKredi• Ayse by 100 in aBank

– These people can • withdraw money form their accounts • Deposit money to their accounts• Transfer monety from one account to another

Page 151: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

151

1992-2007 Pearson Education, Inc. All rights reserved.

Example Bank Accounts (cont.)

• In the test class TestBank– See the balances of accounts– See total balance in each bank– Total transfer revenues of each bank– Total numbr of accounts in each bank

Page 152: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

152

1992-2007 Pearson Education, Inc. All rights reserved.

TestBank classpublic class TestBank { public static void main(String args[]) {// create two banks Bank yKredi = new Bank(“Yapı Kredi “); Bank aBank = new Bank(“Ak Bank “); // create three persons Person ali = new Person(“Ali”,”Ak”); Person veli = new Person(“Veli”,”Ay”); Person ayse = new Person(“Ayşe”,”Ün”);// persons open accounts in different banks Account aliAcc = new Account(ali,1000,yKredi); Account veliAcc = new Account(veli,500,yKredi); Account ayseAcc = new Account(ayse,100,aBank);

Page 153: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

153

1992-2007 Pearson Education, Inc. All rights reserved.

TestBank class

aliAcc.withdraw(200); veliAcc.deposit(100); aliAcc.transfer(veliAcc,100); veliAcc.transfer(ayseAcc,200);// display verious quantities } // end of main} // end of TestBank

Page 154: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

154

1992-2007 Pearson Education, Inc. All rights reserved.

Person class

public class Person { private String name; // each person has a name private String lastName; private Date birthDate; // each has a birth date private long SSN; public Person(String name, String lastName) { …. }// other methods or constructors} // end of class

Page 155: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

155

1992-2007 Pearson Education, Inc. All rights reserved.

Account classpublic class Account { private Person owner; // each account has an ouwner private int accNo; // each account has an account no private Bank bank; // can be opened in a bank – has a bank private double balance;

public Acount(Person owner,initialBalance, Bank b) { this.owner = owner; bank = b; // generate automatically incrementing number of accounts in a bank accNo = b.newAccount(); // or accNo = bank.newAccount(); deposit(initialBalance);}

Page 156: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

156

1992-2007 Pearson Education, Inc. All rights reserved.

Account classpublic void deposit(int deposA) { balance +=deposA; bank.addBalance(depositA); } public void withDraw(int amount) { if(money >= amount) money -=amount; bank.withdraw(amount); } public double getBalance() { return balance;} public Bank getBank() { return bank;}

Page 157: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

157

1992-2007 Pearson Education, Inc. All rights reserved.

Account class (cont.)public void transfer(Acount ac, double amount) { double total = amount; double comussion; if ( bank.equals(ac.getBank()) ) comussion = bank.INTTRCOM; else comussion = Bank.OUTTRCOM; total += comussion; if(total <= getBalance()) { withdraw(total); ac.deposit(amount); bank.addTrRev(comussion); }} // end method transfer } // end class account

Page 158: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

158

1992-2007 Pearson Education, Inc. All rights reserved.

Account class (cont.)

The transfer method – relationship between two accountsCalled on the account from which money will be transferedTakes accout to be tranfered and amout of money as

paramersChecks whether the banks are equal using the equal method

of class objectcalculate comussion rate accordingly

Calculate total as sum of amount plus comussionWithdraw total from the accountDeposit acount to the transfer accountDeposit comussion to the bank maing the transfer

Page 159: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

159

1992-2007 Pearson Education, Inc. All rights reserved.

Account class (cont.)

The equal method a method of the objcect class in java.lang

Returns true if the memory location of two referance variables are the same

Object inmemory,

Bank

a

b

a.equals(b) returns trueOr b.equals(a) the same

What about in Strings?You used that in lab

Page 160: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

160

1992-2007 Pearson Education, Inc. All rights reserved.

Account class (cont.)

• Note that– An account object can reach public methods or variables of

its owner its bank

• To be able to open an accout there should be a bank and person exist

Page 161: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

161

1992-2007 Pearson Education, Inc. All rights reserved.

Bank classpublic class Bank { private String nameOfBank; public final static OUTTRCOM = 2; public final static INTTRCOM = 0.5; private double totalBalance; private double totalTrRev; private int totalNumAcc; public Bank(String name) { nameOfBank = name; } public double getTotalBalance() { return totalBalance; } public double getTotalTrRev() {return totalTrRev; } public void addBalance(double amount) {totalBalance += amount;} public void addTrRev(double amount) {totalTrRev += amount;} public void withdrawBalance(double amount) {totalBalance -= amount;} public int newAccount() { return ++totalNoAcc; }} // end of Bank class you can add other methods or variables

Page 162: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

162

1992-2007 Pearson Education, Inc. All rights reserved.

Bank class - explanations

• When a new account is opened in a bank– Number of accouts is inremented by one

• ++totalNoAcc• The newAccount method also returns incrmented value so as to

assing as the account number– How do we know the total amount of money in a bank?

• When an account owner deposit money to her account• Her balance is incremented• Similarly the total balance of the bank is inreased by the sama

amout• Similarly when somebody witdraws money

– This is a redundent procedure and should be avoided How?

Page 163: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

163

1992-2007 Pearson Education, Inc. All rights reserved.

Bank class - explanations

• OUTTRCOM and INTTRCOM are two final static variables of the Bank class set their initial values and not changed

• Bad design – should be bank specific– Not static variables– Shold not be constants – allowed to be changed – Shold not be public

Page 164: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

164

1992-2007 Pearson Education, Inc. All rights reserved.

Some notes

• Can you use this program in a menu dirven maner

• A user can connect with an ATM or in internet– open an account– Transfer money, withdraw money

• Or banks can monitor their revenues from transfers

• No! - Why? –

Page 165: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

165

1992-2007 Pearson Education, Inc. All rights reserved.

• Here persons, banks and accounts are simple objects created in the TestBank class

• Suppose Ali enter a ank and wants to open an account can the java program execure such a astatement

• Account ali = new Account(“Ali”,”Ak”);• Java is a compiler based a running program can

not criate and exeute such a statement– Note this is possible in other languaes - MATLAB

Page 166: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

166

1992-2007 Pearson Education, Inc. All rights reserved.

Exercise

• Considering the bank problem and its requirements

• Solve the same problem with a different design of classes, possible attibutes and methods

• The same requirements can be satisfied in the test class in many ways

• What is your solution?

Page 167: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

167

1992-2007 Pearson Education, Inc. All rights reserved.

A Better Design

• A diffeent approach to the same problem will be covered in lab

• But each bank has an array of accounts

Page 168: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

168

1992-2007 Pearson Education, Inc. All rights reserved.

Array of Objects

• A bank may have many bank accounts• A store may have many products• A company have many employees• A library or person may have many books• A book has

– One title– One publisher– One publication year– One eddition number– But may have many authors

Page 169: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

169

1992-2007 Pearson Education, Inc. All rights reserved.

Book class

public class Book { private String title; private String publisher; private int publicYear; private int eddition; private String author1,author2, author3,…;// how many authors for a book?// how to write constructors for such a book // with one author two authors and so on..

Page 170: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

170

1992-2007 Pearson Education, Inc. All rights reserved.

Book class with array of autors

public class Book { private String title; // A book has a title private String publisher; // A book has a publisher private int publicYear; // A book has a publication year private int eddition; // an addition number private String authors[]; // but a book has many authors/* array of autor objects each autor is a String or you may

declare autor as an object it self private Author[] authors;Here authors is a array of class Author

Page 171: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

171

1992-2007 Pearson Education, Inc. All rights reserved.

Book class with array of authors - constructor

The constructor of the book classpublic Book(String title,String publicher,int year,.., String[]

authors){ this.title = title; this.publicher = publicher;// takes the author list – parameter and assigns it to the

instance variable this.authors = authors;}

Page 172: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

172

1992-2007 Pearson Education, Inc. All rights reserved.

Bank Example with Array of Objects• To overcome some of the limutations of the pevious

example • Define an array of accounts for each bank

– Yapı kredi has its own array of accounts– Akbank has its own array of accounts

• add a new account to the array – opening new account– bankname.openAcc(person.initailBalance);

• retrieving all objects of that array– Banks total deposits or revenues can be computed eleminating

double entry – Any time summing over exisiting accounts– bankname.totalBalance();

Page 173: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

173

1992-2007 Pearson Education, Inc. All rights reserved.

Bank Example with Array of Objects

• Each account class has a account code – Including the bank code and account code in that

bank• Opperations are performed over bank objects

– Deposit, withdraw money, transfer money– bankname.deposit(accountCode,amount);– bankname.withdraw(accountCode,amount);– bankname.transfer(fromAcc,toBank,toAcc,amount);

Page 174: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

174

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class

• Similar to the previous class accept that• Add a account code composed of a bank code plus

account number in a bank– “yk-001”, “ab-023”

• People refer or mention their accounts by this code

– Withdraw money from accoun “yk-003”– Transter money form “ak-001 to “ak-012”

Page 175: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

175

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class

• Attributes:– Owner – String– Account no – String– Balance - double

• Behavior:– Constructor– Deposit– Withdraw– getBalance– getAccountCode

Page 176: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

176

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class - implementationpublic class Account { private String owner; // each account has an ouwner private String accNo; // each account has an account no private double balance; // no bank object is associated with an account could be changed public Acount(String owner,initialBalance, String accNo) { this.owner = owner; // assign account No // bank = b; bank is not associated with an account // accounts are defined within each bank this.accNo = accNo; // new deposit(initialBalance);}

Page 177: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

177

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class - implementationpublic void deposit(int deposA) { balance +=deposA; } public void withDraw(int amount) { if(money >= amount) balance -=amount; } public double getBalance() { return balance;} public String getAccCode() { return accNo;}} // end calass Account add other methods -

Page 178: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

178

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class• In the test class TestBank2

– Create new banks• yKredi, aBank

– Create new persons• Not needed here as persons are just names String class• “ali ak”,”veli ddd”, “ayşe x”

– These persons can open accounts by depositning an initial amount on a specified bank

• Ali by 1000 in yKredi• Veri by 500 in yKredi• Ayse by 100 in aBank

– These people can • withdraw money form their accounts • Deposit money to their accounts• Transfer monety from one account to another

Page 179: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

179

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class

• In the test class TestBank2– See the balances of individual accounts– See total balance in each bank– Total transfer revenues of each bank– Total numbr of accounts in each bank

Page 180: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

180

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class - Implementationpublic class TestBank2 { public static void main(String args[]) {// create two banks Bank yKredi = new Bank(“Yapı Kredi “,”yk”); Bank aBank = new Bank(“Ak Bank “,””ak”); // create three persons// here not implemented as persons are names // persons open accounts in different banks aBank.openAccount(“ali ak”,100); aBank.openAccount(“veli ddd”,200); yKredi.openAccount(“ayşe x”,300);/* opening an account is a method of a bank people go to banks and

open accounts not interested in accNo or so on only how much money they invest initially and type of account */

Page 181: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

181

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class - Implementation

// deposit or withdraw methods are over banks// specify the account number and moneyaBank.deposit(“ak-001”,200);aBank.withdraw(“ak-002”,50);// transfer methods over banks specify// account code from, account code to, bank to, money//some redundency how do you solve it yKredi.transfer(“yk-001”,aBank,”ak-002”,50);From “yk-001” on yk to “ak-002” on aBank 50 .TL is

transfered

Page 182: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

182

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class - Implementation

// displaying total balance or revenuesSystem.out.println(aBank.displayBalance());System.out.println(yk.displayRev());System.out.println(aBank.displayBalance(“ak-001”)); } // end main} // end class TestBank2

Page 183: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

183

1992-2007 Pearson Education, Inc. All rights reserved.

Note that• In the test class – as an interface

– Users communicate with only banks– The processing of accounts are hidden from the test class

• Users reach their accounts by the account code– Which is sent to the Bank class

• It is the Bank class that has the internal representation of the Accounts

– Arrays in this example– Whereas the test class is unavare of that fact

• Messages originate from the test class – Pass to the Bank class and then– Go to the Account class

Page 184: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

184

1992-2007 Pearson Education, Inc. All rights reserved.

Bank Class• Each bank has an array of accounts

– Account[] accounts;– Has a relationship more then one accounts

• Banks has– Name - String– Code of the bank - String– Number of accounts opened – int– Total Revenue of the bank - double– Commusion rate from transfers – double– List of accounts – Account[]

• Behavior:– Open accounts– Deposit – withdraw– transfer money to or from accounts– Display total balance,– total revenue …

Page 185: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

185

1992-2007 Pearson Education, Inc. All rights reserved.

The Bank class

• public class Bank {• private String name;• private String code;• private int accCount;• private double totalRevenue;• private Account[] accounts;• private static comusionRate = 0.005;• // constructors and methods• } // end of class Bank

Page 186: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

186

1992-2007 Pearson Education, Inc. All rights reserved.

The constructor

• When creating a bank specify its name and code• The constructor creates an array of say 100

accounts– accounts = new Account[100];– 100 Account type refernce variables are created and

assigned the instance variable accounts which is reference to array of Accounts

Page 187: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

187

1992-2007 Pearson Education, Inc. All rights reserved.

Constructor of Bank - implementation

public Bank(String nameOfBank,String bankCode) {

name = nameOfBank; this.bankCode = bankCode; accounts = new Account[100]; //At most 100 Account objects can be refered // we dont use the 0 index in this problem}

Page 188: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

188

1992-2007 Pearson Education, Inc. All rights reserved.

Opening an account

• Gets the name of the person and initial balance from the test class or what ever it sends

• The actions– increment the account count by one– Genteate code for this new account

• Codes are Strings • Banks code + “-” + accont number formattted

– Create an Account object– Assign accounts [accountcount] to the newly created object

Page 189: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

189

1992-2007 Pearson Education, Inc. All rights reserved.

Opening an account

0 1

The new AccoutObject

2

Early accoutsNew index

3

Not used

accouts

Page 190: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

190

1992-2007 Pearson Education, Inc. All rights reserved.

Opening an account - implementation

public void openAccount(String name,double iniBalance) { accCount++; String code = String.format(“%s-%03d” ,bankCode,accCount); accounts[accCount] = new Account(name,code,iniBalance);}

Page 191: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

191

1992-2007 Pearson Education, Inc. All rights reserved.

Deposit money• Called over banks • Takes as parameters the account code • And the amount of money to deposit• Example:

– aBank.deposit(“ak-001”,100)– Deposit 100 TL to the account no “ak-001” opened on aBank

• How it works– Using the account code search the index of the account in the accounts

array by a search method– Get the index of the accout – İf a vaild index is found– Using this index reach the account, call its deposit method– if the account does nıot exisits return false

Page 192: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

192

1992-2007 Pearson Education, Inc. All rights reserved.

Deposit implementation

public boolean deposit(String accCode, double money) { int index = getAccIndex(accCode); if(index !=-1) { accounts[index].deposit(money); return true; } else return false;} // end of method depsit

Page 193: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

193

1992-2007 Pearson Education, Inc. All rights reserved.

Geting account index

• In the test class Accounts are refered by their code

• But internally represented by arrays • So the user specify the code the progrm shold find

the rigth index in the account array – If an account with that code exisits

• A typical search problem• There are build in search methods in java API but

lets develop our method here

Page 194: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

194

1992-2007 Pearson Education, Inc. All rights reserved.

getAccontIndex - implementation

privte int getAccountIndex(String accCode) { for(int i = 1;i <= accCount;i++) if (accCode.equals(accounts[i].getAccCode())) return i; return -1;} // end method• Traverse all the accounts in the bank

• i from 1 to accCount– Compare search accout’s code with the available codes using eth

equals method for Strings – if found return the index– else return -1

Page 195: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

195

1992-2007 Pearson Education, Inc. All rights reserved.

equals() in String class

• equals method in String class• stringName.equals(otherString);• Examples:• String s1 = “Abc”;• String s2 = “abc”;• String s3 = “Ab”;• s1.equals(s2); // false• s1.equals(s2+”c”); // true• equals method imlemented in String class does not

compare memory addreses but content of Strings

Page 196: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

196

1992-2007 Pearson Education, Inc. All rights reserved.

Withdraw money method

• You can do this as an exercise• Also add any display mehtods to the bank class

– Display

• Lets do displayBalance method

Page 197: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

197

1992-2007 Pearson Education, Inc. All rights reserved.

Displaying total balance ina bank

• Here the double entry problem in the previous design is solved as

• Total balance in a bank can be computed by summing the individual accounts’ balances

• How to implement– Make totalBalance zero

• Traverse all opened accounts• Get their balances and add them to totalBalance

– Return totalBalance

Page 198: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

198

1992-2007 Pearson Education, Inc. All rights reserved.

getTotalBalance - implementation

public double getTotalBalance() { double totalBalance = 0.0; for(int i =1; i <= accCount;i++) totalBalance += accounts[i].getBalance(); return totalBalance; } // end of method

Page 199: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

199

1992-2007 Pearson Education, Inc. All rights reserved.

Transfer of money from one accont to another account

• Here lets change the commusion policy say• Transfer within the same bank has no commusion• Transfer among different banks – EFT has:• Commusion is proportional to the ammout of

money to be transfered• Shared by the two banks equally

– Half to a bank the other half to other bank

Page 200: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

200

1992-2007 Pearson Education, Inc. All rights reserved.

• Parameters – From which account: accFrom String– To which bank: bankTo String– To which account accTo– How much money: money

• Notice that specifiying the bank is not needed as in this setting the bank can be optained parsing the account code

– For simplisity paramenter is a bank object it could be the code of the bank as well or no specification for bank

Page 201: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

201

1992-2007 Pearson Education, Inc. All rights reserved.

• Since accounts can be reached with their indesis• if the two banks are equal

– Withdraw from one account deposit to the other the same money without any commusions

• withdraw(accFrom,money);• deposit(accTo,money);

– What is the drawbak of this ?

Page 202: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

202

1992-2007 Pearson Education, Inc. All rights reserved.

• if the two banks are different– Calculate commusion – Calculate total– Withdraw money from accFrom in the same bank– if money is succesfully withdrawn

• Add half of the commusion to this bank where transfer is made from

• Deposit money to the accTo in the other bank• Add other half of commusion to the bankTo’s revenues

Page 203: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

203

1992-2007 Pearson Education, Inc. All rights reserved.

getTotalRevenue

• Returns the total revenue of the bank from transfers

• Implementation:• public double getTotalRevenue() {• return totalRevenue;• } // end of method

Page 204: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

204

1992-2007 Pearson Education, Inc. All rights reserved.

Simple bank class with array of Accounts

• Develop a Bank class hoding a fixed number of accounts as an array of objects. Each element of the array is a reference to an Account object

• The Account class is a typical of our accounts having balnace, owner and account code as instance variables and deposit, withdraw, get and set or other relevant methods.

– Such an Account class is presented in the next slides

• The Bank class– Declares and initilize the array of accounts – Create new Account objects and add to the array– Calculates the total balance in the bank

Page 205: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

205

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class

• Similar to the previous account class accept that• Add a account code composed of a bank code plus

account number in a bank– “yk-001”, “ab-023”

• In proactice people refer to their accounts by this code

– Withdraw money from accoun “yk-003”– Deposit money to accoun “yk-003”– See the balance of “yk-003”

Page 206: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

206

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class

• Attributes:– Owner : String– Account no : String– Balance : double

• Behavior:– Constructor– Deposit– Withdraw– getBalance– getAccountCode

Page 207: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

207

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class - implementation

public class Account { private String owner; // each account has an ouwner private String accNo; // each account has an account no private double balance; public Acount(String owner,initialBalance, String accNo)

{ this.owner = owner; this.accNo = accNo; // new deposit(initialBalance);}

Page 208: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

208

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class - implementationpublic void deposit(double deposA) { balance +=deposA; } public boolean withDraw(double amount) { if(balance >= amount) { balance -=amount; return ture; } else return false; } public double getBalance() { return balance; } public String getAccCode() { return accNo; }} // end calass Account add other methods -

Page 209: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

209

1992-2007 Pearson Education, Inc. All rights reserved.

The Bank class

• Initilize an array of say 100 accounts• Create individual accounts and assing to the

arrray to Accounts objects• Calculate and display the total money currently

in the bank • Finally closes one of the accounts

Page 210: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

210

1992-2007 Pearson Education, Inc. All rights reserved.

The Bank class - implementation

public class Bank { main() { /* each element is a reference to an Account object. When

initilized having null values */ Account[] accounts = new Accounts[100]; // creates an Account object Account a1 = new Account(“ali”,”yk-001”,100); // assing it as the first element of the accounts arrray accounts[0] = a1; // creates second Account object and assing it as the second

element of the accounts arrray accounts[1] = new Account(“ayse”,”yk-002”,500);

Page 211: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

211

1992-2007 Pearson Education, Inc. All rights reserved.

The Bank class - implementation

// calcualte and print total money in the bank double totalBalance = 0.0; for (int i =0; i <accounts.length ;i++) if(accounts[i] <> null) totalBalance += accounts[i]; System.out.println(“Total Balance:” + totalBalance); accounts[0] = null;// first account is closed: deleted from the array of accounts } // end main method} // end Bank class

Page 212: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

212

1992-2007 Pearson Education, Inc. All rights reserved.

Assinging an Account to the accounts array

0 1

The new AccoutObject

2

Early accoutsNew index

3

Not used

accouts

null null

Page 213: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

213

1992-2007 Pearson Education, Inc. All rights reserved.

Bank Example with Array of Objects• To overcome some of the limutations of the pevious

example • Define an array of accounts for each bank

– Yapı kredi has its own array of accounts– Akbank has its own array of accounts

• add a new account to the array – opening new account– bankname.openAcc(person.initailBalance);

• retrieving all objects of that array– Banks total deposits or revenues can be computed eleminating

double entry – Any time summing over exisiting accounts– bankname.totalBalance();

Page 214: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

214

1992-2007 Pearson Education, Inc. All rights reserved.

Bank Example with Array of Objects

• Each account class has a account code – Including the bank code and account code in that

bank• Opperations are performed over bank objects

– Deposit, withdraw money, transfer money– bankname.deposit(accountCode,amount);– bankname.withdraw(accountCode,amount);– bankname.transfer(fromAcc,toBank,toAcc,amount);

Page 215: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

215

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class• In the test class TestBank2

– Create a bank• yKredi

– Create new persons• Not needed here as persons are just names String class• “ali ak”,”veli ddd”, “ayşe x”

– These persons can open accounts by depositning an initial amount on a specified bank

• Ali by 1000 in yKredi• Veri by 500 in yKredi

– These people can • withdraw money form their accounts • Deposit money to their accounts

Page 216: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

216

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class

• In the test class TestBank2– See the balances of individual accounts– See total balance in each bank– Total transfer revenues of each bank– Total numbr of accounts in each bank

Page 217: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

217

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class - Implementationpublic class TestBank2 { public static void main(String args[]) {// create a bank Bank aBank = new Bank(“Ak Bank “,”yk”); // create three persons// here not implemented as persons are names // persons open accounts in different banks aBank.openAccount(“ali ak”,100); aBank.openAccount(“veli ddd”,200); aBank.openAccount(“ayşe x”,300);/* opening an account is a method of a bank people go to banks and

open accounts not interested in accNo or so on only how much money they invest initially and type of account */

Page 218: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

218

1992-2007 Pearson Education, Inc. All rights reserved.

The Test Class - Implementation

// deposit or withdraw methods are over banks// specify the account number and money aBank.deposit(“ak-001”,200); aBank.withdraw(“ak-002”,50);// displaying total balance or revenues System.out.println(aBank.displayBalance()); System.out.println(aBank.displayBalance(“ak-001”)); } // end main} // end class TestBank2

Page 219: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

219

1992-2007 Pearson Education, Inc. All rights reserved.

Note that• In the test class – as an interface

– Users communicate with only banks– The processing of accounts are hidden from the test class

• Users reach their accounts by the account code– Which is sent to the Bank class

• It is the Bank class that has the internal representation of the Accounts

– Arrays in this example– Whereas the test class is unavare of that fact

• Messages originate from the test class – Pass to the Bank class and then– Go to the Account class

Page 220: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

220

1992-2007 Pearson Education, Inc. All rights reserved.

The Account Class

• The account class used in the previous example is used

Page 221: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

221

1992-2007 Pearson Education, Inc. All rights reserved.

Bank Class• Each bank has an array of accounts

– Account[] accounts;– Has a relationship more then one accounts

• Banks has– Name - String– Code of the bank - String– Number of accounts opened – int– Total Revenue of the bank - double– Commusion rate from transfers – double– List of accounts – Account[]

• Behavior:– Open accounts– Deposit – withdraw– transfer money to or from accounts– Display total balance,– total revenue …

Page 222: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

222

1992-2007 Pearson Education, Inc. All rights reserved.

The Bank class

• public class Bank {• private String name;• private String code;• private int accCount;• private double totalRevenue;• private Account[] accounts;• private static comusionRate = 0.005;• // constructors and methods• } // end of class Bank

Page 223: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

223

1992-2007 Pearson Education, Inc. All rights reserved.

The constructor

• When creating a bank specify its name and code• The constructor creates an array of say 100

accounts– accounts = new Account[100];– 100 Account type refernce variables are created and

assigned the instance variable accounts which is reference to array of Accounts

Page 224: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

224

1992-2007 Pearson Education, Inc. All rights reserved.

Constructor of Bank - implementation

public Bank(String nameOfBank,String bankCode) {

name = nameOfBank; this.bankCode = bankCode; accounts = new Account[100]; //At most 100 Account objects can be refered // we dont use the 0 index in this problem}

Page 225: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

225

1992-2007 Pearson Education, Inc. All rights reserved.

Opening an account

• Gets the name of the person and initial balance from the test class or what ever it sends

• The actions– increment the account count by one– Genteate code for this new account

• Codes are Strings • Banks code + “-” + accont number formattted

– Create an Account object– Assign accounts [accountcount] to the newly created object

Page 226: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

226

1992-2007 Pearson Education, Inc. All rights reserved.

Opening an account

0 1

The new AccoutObject

2

Early accoutsNew index

3

Not used

accouts

Page 227: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

227

1992-2007 Pearson Education, Inc. All rights reserved.

Opening an account - implementation

public void openAccount(String name,double iniBalance) { accCount++; String code = String.format(“%s-%03d” ,bankCode,accCount); accounts[accCount] = new Account(name,code,iniBalance);}

Page 228: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

228

1992-2007 Pearson Education, Inc. All rights reserved.

Deposit money• Called over banks • Takes as parameters the account code • And the amount of money to deposit• Example:

– aBank.deposit(“ak-001”,100)– Deposit 100 TL to the account no “ak-001” opened on aBank

• How it works– Using the account code search the index of the account in the accounts

array by a search method– Get the index of the accout – If a vaild index is found– using this index reach the account, call its deposit method– if the account does nıot exisits – return false

Page 229: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

229

1992-2007 Pearson Education, Inc. All rights reserved.

Deposit implementation

public boolean deposit(String accCode, double money) { int index = getAccIndex(accCode); if(index !=-1) { accounts[index].deposit(money); return true; } else return false;} // end of method depsit

Page 230: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

230

1992-2007 Pearson Education, Inc. All rights reserved.

Geting account index

• In the test class Accounts are refered by their code

• But internally represented by arrays • So the user specify the code the progrm shold find

the rigth index in the account array – If an account with that code exisits

• A typical search problem• There are build in search methods in java API but

lets develop our method here

Page 231: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

231

1992-2007 Pearson Education, Inc. All rights reserved.

getAccontIndex - implementation

privte int getAccountIndex(String accCode) { for(int i = 1;i <= accCount;i++) if (accCode.equals(accounts[i].getAccCode())) return i; return -1;} // end method• Traverse all the accounts in the bank

• i from 1 to accCount– Compare search accout’s code with the available codes using eth

equals method for Strings – if found return the index– else return -1

Page 232: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

232

1992-2007 Pearson Education, Inc. All rights reserved.

equals() in String class

• equals method in String class• stringName.equals(otherString);• Examples:• String s1 = “Abc”;• String s2 = “abc”;• String s3 = “Ab”;• s1.equals(s2); // false• s1.equals(s2+”c”); // true• equals method imlemented in String class does not

compare memory addreses but content of Strings

Page 233: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

233

1992-2007 Pearson Education, Inc. All rights reserved.

Withdraw money method

• You can do this as an exercise

Page 234: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

234

1992-2007 Pearson Education, Inc. All rights reserved.

Displaying total balance in a bank

• Here the double entry problem in the previous design is solved as

• Total balance in a bank can be computed by summing the individual accounts’ balances

• How to implement– Make totalBalance zero

• Traverse all opened accounts• Get their balances and add them to totalBalance

– Return totalBalance

Page 235: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

235

1992-2007 Pearson Education, Inc. All rights reserved.

getTotalBalance - implementation

public double getTotalBalance() { double totalBalance = 0.0; for(int i =1; i <= accCount;i++) totalBalance += accounts[i].getBalance(); return totalBalance; } // end of method

Page 236: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

236

1992-2007 Pearson Education, Inc. All rights reserved.

Get accout balace

• Write a method for returning the balance of individual accounts

• The method should be invoked over bank objects , will get the account code as a String argument and return the balance of the account

Page 237: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

237

1992-2007 Pearson Education, Inc. All rights reserved.

A Singel Store Example

• In a single store there may be many products• Many customers • Many employees

Page 238: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

238

1992-2007 Pearson Education, Inc. All rights reserved.

Exercise A Single Store

• There is a simple store selling products to its customers. From the screen the opperatior can sell products, order products, montor amount of money in the cash, see the performance of the employees, register new customers, see the summary of customer purchases.

• Develop a menu driven java application to atchive these functionalities from command window.

Page 239: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

239

1992-2007 Pearson Education, Inc. All rights reserved.

The Product

• Attributes of products are:– Name– Description– Product code – Purchase and selling price– Number in stock

• Products can be:– Ordered– Sold– Cheked in stock– and other get and set opperations seting prices …

Page 240: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

240

1992-2007 Pearson Education, Inc. All rights reserved.

The Customer

• Loyal customer are registered and followed up by their loyalty cards

• Attributes:– Name– Birth day…– Total accumulated points

• Customers can use thier total points in purchasing or can get discounts from these points

– As customers purchase their points are accumulated

Page 241: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

241

1992-2007 Pearson Education, Inc. All rights reserved.

The Employee

• Employees are geting commusins from the sales they made

• If the employee who made the sale is known they some commusions are accumulating for them

• Attributes:– Name – Employee number– Total commusion accumulated

Page 242: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

242

1992-2007 Pearson Education, Inc. All rights reserved.

Sales Transactions

• Each sale is definitly involve one or more products

– its stock are dimenishes– 2 shirts 1 suck e.g.

• Optionally each sale may include the custormer if a registered one and the employee who mede the sell

• The customer accumulates points and optionally use some of her accumulated points

• The sale person accumululates commusions

Page 243: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

243

1992-2007 Pearson Education, Inc. All rights reserved.

The Store• Can do the following for each entity type• For products

– Define new products– sell products – Order prducts– Set selling and ordering prices of products

• For custormer– Register new customers– Monitor each customer

• For sale person– New personal– Monitor their performance– Change commusion rate – same for all employeess

Page 244: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

244

1992-2007 Pearson Education, Inc. All rights reserved.

The Store (cont.)

• For sales transactions– For each sale transaction get of products and their

amounts (how many units are sold) are entered optionally with customer and employee ID

– Display to the customer • Total amount• Customers total points

– Ask the customer to use her accumulated points– Get the money

• For cash– See total money in store

Page 245: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

245

1992-2007 Pearson Education, Inc. All rights reserved.

8.14  Software Reusability

• Rapid application development– Software reusability speeds the development of powerful,

high-quality software

• Java’s API– provides an entire framework in which Java developers

can work to achieve true reusability and rapid application development

– Documentation:• java.sun.com/javase/6/docs/api/• Or http://java.sun.com/javase/downloads/index.jsp to

download

Page 246: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

246

1992-2007 Pearson Education, Inc. All rights reserved.

8.15  Data Abstraction and Encapsulation

• Data abstraction– Information hiding

• Classes normally hide the details of their implementation from their clients

– Abstract data types (ADTs)• Data representation

– example: primitive type int is an abstract representation of an integer• ints are only approximations of integers, can

produce arithmetic overflow• Operations that can be performed on data

Page 247: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

247

1992-2007 Pearson Education, Inc. All rights reserved.

Avoid reinventing the wheel. Study the capabilities of the Java API. If the API contains a class that meets your program’s requirements, use that class rather than create your own.

Good Programming Practice 8.2

Page 248: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

248

1992-2007 Pearson Education, Inc. All rights reserved.

8.15  Data Abstraction and Encapsulation (Cont.)

• Queues– Similar to a “waiting line”

• Clients place items in the queue (enqueue an item)• Clients get items back from the queue (dequeue an item)• First-in, first out (FIFO) order

– Internal data representation is hidden• Clients only see the ability to enqueue and dequeue items

Page 249: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

249

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.15

5Programmers create types through the class mechanism. New types can be designed to be as convenient to use as the built-in types. This marks Java as an extensible language. Although the language is easy to extend via new types, the programmer cannot alter the base language itself.

Page 250: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

250

1992-2007 Pearson Education, Inc. All rights reserved.

8.16  Time Class Case Study: Creating Packages

• To declare a reusable class– Declare a public class– Add a package declaration to the source-code file

• must be the first executable statement in the file• package name should consist of your Internet domain name

in reverse order followed by other names for the package– example: com.deitel.jhtp7.ch08– package name is part of the fully qualified class name

• Distinguishes between multiple classes with the same name belonging to different packages

• Prevents name conflict (also called name collision)– Class name without package name is the simple name

Page 251: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

251

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Time1.java

(1 of 2)

1 // Fig. 8.18: Time1.java 2 // Time1 class declaration maintains the time in 24-hour format. 3 package com.deitel.jhtp7.ch08; 4 5 public class Time1 6 { 7 private int hour; // 0 - 23 8 private int minute; // 0 - 59 9 private int second; // 0 - 59 10 11 // set a new time value using universal time; perform 12 // validity checks on the data; set invalid values to zero 13 public void setTime( int h, int m, int s ) 14 { 15 hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour 16 minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute 17 second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second 18 } // end method setTime 19

package declaration

Time1 is a public class so it can be used by importers of this package

Page 252: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

252

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Time1.java

(2 of 2)

20 // convert to String in universal-time format (HH:MM:SS) 21 public String toUniversalString() 22 { 23 return String.format( "%02d:%02d:%02d", hour, minute, second ); 24 } // end method toUniversalString 25 26 // convert to String in standard-time format (H:MM:SS AM or PM) 27 public String toString() 28 { 29 return String.format( "%d:%02d:%02d %s", 30 ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), 31 minute, second, ( hour < 12 ? "AM" : "PM" ) ); 32 } // end method toString 33 } // end class Time1

Page 253: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

253

1992-2007 Pearson Education, Inc. All rights reserved.

8.16  Time Class Case Study: Creating Packages (Cont.)

– Compile the class so that it is placed in the appropriate package directory structure

• Example: our package should be in the directorycom

deiteljhtp7

ch08• javac command-line option –d

– javac creates appropriate directories based on the class’s package declaration

– A period (.) after –d represents the current directory

Page 254: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

254

1992-2007 Pearson Education, Inc. All rights reserved.

8.16  Time Class Case Study: Creating Packages (Cont.)

– Import the reusable class into a program• Single-type-import declaration

– Imports a single class– Example: import java.util.Random;

• Type-import-on-demand declaration– Imports all classes in a package– Example: import java.util.*;

Page 255: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

255

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.12

Using the import declaration import java.*; causes a compilation error. You must specify the exact name of the package from which you want to import classes.

Page 256: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

256

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Time1PackageTest

.java

(1 of 2)

1 // Fig. 8.19: Time1PackageTest.java 2 // Time1 object used in an application. 3 import com.deitel.jhtp6.ch08.Time1; // import class Time1 4 5 public class Time1PackageTest 6 { 7 public static void main( String args[] ) 8 { 9 // create and initialize a Time1 object 10 Time1 time = new Time1(); // calls Time1 constructor 11 12 // output string representations of the time 13 System.out.print( "The initial universal time is: " ); 14 System.out.println( time.toUniversalString() ); 15 System.out.print( "The initial standard time is: " ); 16 System.out.println( time.toString() ); 17 System.out.println(); // output a blank line 18

Single-type import declaration

Refer to the Time1 class by its simple name

Page 257: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

257

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Time1PackageTest

.java

(2 of 2)

19 // change time and output updated time 20 time.setTime( 13, 27, 6 ); 21 System.out.print( "Universal time after setTime is: " ); 22 System.out.println( time.toUniversalString() ); 23 System.out.print( "Standard time after setTime is: " ); 24 System.out.println( time.toString() ); 25 System.out.println(); // output a blank line 26 27 // set time with invalid values; output updated time 28 time.setTime( 99, 99, 99 ); 29 System.out.println( "After attempting invalid settings:" ); 30 System.out.print( "Universal time: " ); 31 System.out.println( time.toUniversalString() ); 32 System.out.print( "Standard time: " ); 33 System.out.println( time.toString() ); 34 } // end main 35 } // end class Time1PackageTest 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

Page 258: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

258

1992-2007 Pearson Education, Inc. All rights reserved.

8.16  Time Class Case Study: Creating Packages (Cont.)

• Class loader– Locates classes that the compiler needs

• First searches standard Java classes bundled with the JDK• Then searches for optional packages

– These are enabled by Java’s extension mechanism• Finally searches the classpath

– List of directories or archive files separated by directory separators

• These files normally end with .jar or .zip• Standard classes are in the archive file rt.jar

Page 259: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

259

1992-2007 Pearson Education, Inc. All rights reserved.

8.16  Time Class Case Study: Creating Packages (Cont.)

• To use a classpath other than the current directory

– -classpath option for the javac compiler– Set the CLASSPATH environment variable

• The JVM must locate classes just as the compiler does

– The java command can use other classpathes by using the same techniques that the javac command uses

Page 260: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

260

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 8.13

Specifying an explicit classpath eliminates the current directory from the classpath. This prevents classes in the current directory (including packages in the current directory) from loading properly. If classes must be loaded from the current directory, include a dot (.) in the classpath to specify the current directory.

Page 261: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

261

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 8.16

In general, it is a better practice to use the -classpath option of the compiler, rather than the CLASSPATH environment variable, to specify the classpath for a program. This enables each application to have its own classpath.

Page 262: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

262

1992-2007 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 8.3

Specifying the classpath with the CLASSPATH environment variable can cause subtle and difficult-to-locate errors in programs that use different versions of the same package.

Page 263: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

263

1992-2007 Pearson Education, Inc. All rights reserved.

8.17  Package Access

• Package access– Methods and variables declared without any access

modifier are given package access– This has no effect if the program consists of one class– This does have an effect if the program contains multiple

classes from the same package• Package-access members can be directly accessed through

the appropriate references to objects in other classes belonging to the same package

Page 264: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

264

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PackageDataTest

.java

(1 of 2)

1 // Fig. 8.20: PackageDataTest.java 2 // Package-access members of a class are accessible by other classes 3 // in the same package. 4 5 public class PackageDataTest 6 { 7 public static void main( String args[] ) 8 { 9 PackageData packageData = new PackageData(); 10 11 // output String representation of packageData 12 System.out.printf( "After instantiation:\n%s\n", packageData ); 13 14 // change package access data in packageData object 15 packageData.number = 77; 16 packageData.string = "Goodbye"; 17 18 // output String representation of packageData 19 System.out.printf( "\nAfter changing values:\n%s\n", packageData ); 20 } // end main 21 } // end class PackageDataTest 22

Can directly access package-access members

Page 265: 1 - boun.edu.trmisprivate.boun.edu.tr/badur/MIS132/MIS 2… · PPT file · Web view · 2011-10-24In the test class TestBank Create new banks ... com.deitel.jhtp7.ch08 package name

265

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PackageDataTest

.java

(2 of 2)

23 // class with package access instance variables 24 class PackageData 25 { 26 int number; // package-access instance variable 27 String string; // package-access instance variable 28 29 // constructor 30 public PackageData() 31 { 32 number = 0; 33 string = "Hello"; 34 } // end PackageData constructor 35 36 // return PackageData object String representation 37 public String toString() 38 { 39 return String.format( "number: %d; string: %s", number, string ); 40 } // end method toString 41 } // end class PackageData After instantiation: number: 0; string: Hello After changing values: number: 77; string: Goodbye

Package-access instance variables