Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Object-Oriented Programming: Using Classes

Similar presentations


Presentation on theme: "Introduction to Object-Oriented Programming: Using Classes"— Presentation transcript:

1 Introduction to Object-Oriented Programming: Using Classes
Chapter 3 Introduction to Object-Oriented Programming: Using Classes

2 Topics Class Basics and Benefits Creating Objects Using Constructors
Calling Methods Using Object References Calling Static Methods and Using Static Class Variables Using Predefined Java Classes

3 Object-Oriented Programming
Classes combine data and the methods (code) to manipulate the data Classes are a template used to create specific objects All Java programs consist of at least one class. Two types of classes Application/Applet classes Service classes

4 Why Use Classes? Usually, the data for a program is not simply one item. Often we need to manage entities like students, books, flights, etc. We need to be able to manipulate such entities as a unit. Classes allow us to separate the data for each object, while using common code to manipulate each object.

5 Example Student class Student object
Data: name, year, and grade point average Methods: store/get the value of the data, promote to next year, etc. Student object Object name: student1 Data: Maria Gonzales, Sophomore, 3.5

6 Objects Object reference Instantiating an object Instance of the class
an identifier of the object Instantiating an object creating an object of a class; assigns initial values to the object data. Objects need to be instantiated before being used Instance of the class an object after instantiation

7 Class Members Members of a class Fields fields can be: Methods
the class' fields and methods Fields instance variables and static variables (we'll define static later) Instance variables variables defined in the class and given a value in each object fields can be: any primitive data type (int, double, etc.) objects of the same or another class Methods the code to manipulate the object data

8 Encapsulation Instance variables are usually declared to be private, which means that they cannot be accessed directly outside the class. Users (clients) of the class can only reference the private data of an object by calling methods of the class. Thus the methods provide a protective shell around the data. We call this encapsulation. Benefit: the class’ methods can ensure that the object data is always valid.

9 Naming Conventions Class names: start with a capital letter
Object references: start with a lowercase letter In both cases, internal words start with a capital letter Example: classes: Student, PetAnimal objects: marcusAustin, myBoaConstrictor

10 Reusability Reuse class code is already written and tested new applications can be built faster the applications will be more reliable Example: A Date class could be used in a calendar program, appointment-scheduling program, online shopping program, etc.

11 How to Reuse a Class You don't need to know how the class is written or see the code of the class You do need to know the application programming interface (API) of the class. The API is published and tells you: how to create objects what methods are available how to call the methods

12 1. Declare an Object Reference
An object reference holds the address of the object Syntax to declare an object reference: ClassName objectReference; or ClassName objectRef1, objectRef2…; Example: SimpleDate d1;

13 2. Instantiate an Object Objects must be instantiated before they can be used Call a constructor using the new keyword constructor: a special method that creates an object and assigns initial values to data A constructor has the same name as the class. Syntax: objectReference = new ClassName( arg list ); Arg list (argument list) is comma-separated list of initial values to assign to the object data

14 SimpleDate Class Constructors
SimpleDate Class API SimpleDate Class Constructors SimpleDate( ) creates a SimpleDate object with initial month, day, and year values of 1, 1, 2000 SimpleDate( int mm, int dd, int yy ) creates a SimpleDate object with initial month, day, and year values of mm, dd, and yy

15 Instantiation Examples
SimpleDate independenceDay; independenceDay = new SimpleDate( 7, 4, 1776 ); SimpleDate nextCentury = new SimpleDate( 1, 1, 2101 ); SimpleDate defaultDate = new SimpleDate( ); See Example 3.1 Constructors.java

16 Objects After Instantiation

17 Calling a Method

18 Method Classifications
Accessor methods “get” methods return the current values of object data Mutator methods “set” methods change the values of object data

19 SimpleDate Accessor Methods
Return value Method name and argument list int getMonth( ) returns the value of month getDay( ) returns the value of day getYear( ) returns the value of year

20 SimpleDate Mutator Methods
Return value Method name and argument list void setMonth( int mm ) sets the value of month to mm. If mm is not a valid month, sets month to 1. setDay( int dd ) sets the value of day to dd. If dd is not a valid day, sets day to 1. setYear( int yy ) sets the value of year to yy

21 Dot Notation Use when calling a method, you need to specify which object the method should use. Syntax: objectReference.methodName( arg1, arg2, … )

22 Method Return Values Can be a primitive data type, class type, or void
Value-returning method The method returns a value. Thus the method call is used in an expression. When the expression is evaluated, the return value of the method replaces the method call. Methods with a void return type Do not return a value Method call is complete statement (ends with ;)

23 The Argument List in an API
Comma-separated pairs of dataType variableName The argument list specifies: The order of the arguments The data type of each argument Arguments can be: Any expression that evaluates to the specified data type

24 Reading an API: Value-returning Method
int getMonth( ) return value method name is the method takes is an int getMonth no arguments Example method calls (assuming d1 is a SimpleDate object): int m = d1.getMonth( ); or System.out.println( d1.getMonth( ) );

25 Reading an API: void Method
void setMonth( int newMonth ) method does method name is the method takes one not return setMonth argument: an int a value Example method call (assuming d1 is a SimpleDate object): d1.setMonth( 12 ); See Example 3.2 Methods.java

26 Common Error Trap When calling a method, include only expressions in your argument list. Including data types in your argument list will cause a compiler error. If the method takes no arguments, remember to include the empty parentheses after the method's name. The parentheses are required even if there are no arguments.

27 Object Reference vs. Object Data
Object references point to the memory location of object data. An object can have multiple object references pointing to it. Or an object can have no object references pointing to it. If so, the garbage collector will free the object's memory See Example 3.3 ObjectReferenceAssignment.java

28 Two References to an Object
After Example 3.3 runs, two object references point to the same object

29 null Object References
An object reference can point to no object. In that case, the object reference has the value null Object references have the value null when they have been declared, but have not been used to instantiate an object. Attempting to use a null object reference causes a NullPointerException at run time. See Example 3.4 NullReference.java and Example 3.5 NullReference2.java

30 Using Java Predefined Classes
Java Packages The String Class Formatting Output using DecimalFormat The Random class Console Input Using the Scanner Class Using static methods and data Using System and the PrintStream class The Math Class Formatting Output using NumberFormat The Wrapper Classes Dialog Boxes

31 Java Predefined Classes
The Java SDK provides more than 2,000 classes that can be used to add functionality to our programs APIs for Java classes are published on Oracle’s website: Also see Appendix F

32 Java Packages Classes are grouped in packages according to functionality. Package Categories of Classes java.lang Basic functionality common to many programs, such as the String class and the Math class java.awt Graphics classes for drawing and using colors javax.swing User-interface components java.text Classes for formatting numeric output java.util The Scanner class, the Random class and other miscellaneous utility classes java.io Classes for reading from and writing to files

33 Using a Class From a Package
Classes in java.lang are automatically available. Classes in other packages need to be "imported" using this syntax: import package.ClassName; or import package.*; (imports all required classes from package) Example import java.text.DecimalFormat; import java.text.*;

34 The String Class String Constructors
Represents a sequence of characters Examples: String greeting = new String( "Hello" ); String empty = new String( ); String Constructors String( String str ) allocates a String object with the value of str, which is a String object or a String literal String( ) allocates an empty String object

35 String Concatenation Operators
appends a String to another String. At least one operand must be a String. += shortcut String concatenation operator Example: String s1 = new String( "Hello " ); String s2 = "there"; String s3 = s1 + s2; // s3 is: // Hello there String s3 += "!"; // s3 is now: // Hello there!

36 The length Method Return type Method name and argument list Example
int length( ) returns the number of characters in the String Example String greeting = "Hello"; int len = greeting.length( ); The value of len is 5

37 toUpperCase and toLowerCase Methods
Return type Method name and argument list String toUpperCase( ) returns a copy of the String with all letters uppercase toLowerCase( ) returns a copy of the String with all letters lowercase Example: String greeting = "Hello"; greeting = greeting.toUpperCase( ); The value of greeting is "HELLO"

38 The indexOf Methods String greeting = "Hello"; Return type
Method name and argument list int indexOf( String searchString ) returns the index of the first occurrence of searchString, or -1 if not found indexOf( char searchChar ) returns the index of the first occurrence of searchChar, or if not found The index of the first character of a String is 0. Example: String greeting = "Hello"; int index = greeting.indexOf( 'e' ); The value of index is 1.

39 The charAt Method Return type Method name and argument list Example
charAt( int index ) returns the character at index index Example String greeting = "Hello"; char firstChar = greeting.charAt( 0 ); The value of firstChar is 'H'

40 The substring Method See Example 3.6 StringDemo.java Return type
Method name and argument list String substring( int startIndex, int endIndex ) returns a substring of the String object beginning at the character at index startIndex and ending at the character at index endIndex – 1 Example: String greeting = "Hello"; String endOfHello = greeting.substring( 3, hello.length( ) ); The value of endOfHello is “lo” See Example 3.6 StringDemo.java

41 Common Error Trap Specifying a negative start index or a start index past the last character of the String will generate a StringIndexOutOfBoundsException Specifying a negative end index or an end index greater than the length of the String also will generate a StringIndexOutOfBoundsException

42 Formatting Numeric Output
The DecimalFormat class and the NumberFormat class allow you to specify the number of digits for printing and to add dollar signs and percent signs to your output. Both classes are in the java.text package. We will cover the NumberFormat class later.

43 The DecimalFormat Class
DecimalFormat Constructor DecimalFormat( String pattern ) instantiates a DecimalFormat object with the format specified by pattern Pattern characters: required digit, include if 0 # optional digit, suppress if 0 decimal point , comma separator % multiply by 100 and display a percent sign

44 The DecimalFormat format Method
To format a numeric value for output, call the format method. See Example 3.7 DemoDecimalFormat.java Return type Method name and argument list String format( double number ) returns a formatted String representation of number

45 Random Class Constructor
The Random Class Generates a pseudorandom number (appearing to be random, but mathematically calculated) The Random class is in the java.util package. Example: Random rand = new Random( ); Random Class Constructor Random( ) Creates a random number generator.

46 The nextInt Method Example:
Return type Method name and argument list int nextInt( int number ) returns a random integer ranging from 0 up to, but not including, number Example: to generate a random integer between 1 and 6: int die = rand.nextInt( 6 ) + 1; See Example 3.8 RandomNumbers.java

47 Input Using the Scanner Class
Provides methods for reading byte, short, int, long, float, double, and String data types from the Java console and other sources Scanner is in the java.util package Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.)

48 A Scanner Constructor Example:
Scanner scan = new Scanner( System.in ); Scanner Constructor Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console

49 Scanner next… Methods Return type Method name and argument list
dataType nextDataType( ) returns the next token in the input stream. dataType can be byte, int, short, long, float, double, or boolean String next( ) returns the next token in the input stream as a String nextLine( ) returns the remainder of the line as a String

50 Prompting the User The next… methods do not prompt the user for an input value Use System.out.print to print the prompt, then call the next… method. Example: Scanner scan = new Scanner( System.in ); System.out.print( "Enter your age > " ); int age = scan.nextInt( ); See Example 3.9 DataInput.java

51 End your prompts with an indication that input is expected.
SOFTWARE ENGINEERING TIP End your prompts with an indication that input is expected. Include a trailing space for readability. Example: System.out.print( "Enter your age > " );

52 SOFTWARE ENGINEERING TIP
Provide the user with clear prompts for input. Prompts should use words the user understands and should describe the data requested as well as any restrictions on valid input values. Example: Enter your first and last name > or Enter an integer between 0 and 10 >

53 Character Input Scanner does not have a nextChar method.
To read a single character, read the input as a String, then extract the first character of the String into a char variable. Example: System.out.print( "Enter your " "middle initial > " ); String initialS = scan.next( ); char initial = initialS.charAt( 0 ); See Example 3.10 CharacterInput.java

54 Reading A Whole Line The next method will read only one word of String input because the space is a white space character. To read a whole line, including spaces, use the nextLine method. Example: System.out.print( "Enter a sentence > " ); String sentence = scan.nextLine( ); See Example 3.11 InputALine.java

55 static Methods Also called class methods
Can be called without instantiating an object Might provide some quick, one-time functionality; for example, popping up a dialog box or executing a math function In the method API, the keyword static precedes the return type.

56 Calling static Methods
Use the dot syntax with the class name instead of the object reference Syntax: ClassName.methodName( argument list ) Example: int absValue = Math.abs( -9 ); abs is a static method of the Math class that returns the absolute value of the argument. (Here, the argument is -9, and the value 9 would be returned from the method and assigned to the variable absValue.)

57 static Class Data Syntax: ClassName.staticDataName Example: Color.BLUE
BLUE is a static constant of the Color class.

58 The System Class The System class is in the java.lang package, so it does not need to be imported. static constants of the System class in represents the standard input device (the keyboard by default). in is an object of the InputStream class out represents the standard output device (the Java console by default). out is an object of the PrintStream class Examples Scanner scan = new Scanner( System.in ); System.out.println( "Hello" );

59 Using System.out Example: The output is: Return type
System.out.print( "The answer is " ); System.out.println( 3 ); The output is: The answer is 3 Return type Method name and argument list void print( anyDataType argument ) prints argument to the standard output device println( anyDataType argument ) prints argument to the standard output device followed by a newline character

60 The toString Method See Example 3.12 PrintDemo.java Return type
Method name and argument list String toString( ) converts the object data to a String All classes have a toString method. Its purpose is to return a String representing the data of the object. The toString method is called automatically (implicitly) when an object reference is used with the print or println methods. See Example 3.12 PrintDemo.java

61 The exit Method Return type Method name and argument list
void exit( int exitStatus ) static method that terminates the Java Virtual Machine. A value of 0 for exitStatus indicates normal termination. Any other values indicate abnormal termination and are used to signal that the program ended because an error occurred. The static exit method can be useful to stop execution at a place other than the normal end of the program. Example: System.exit( 0 );

62 The Math Class The Math class provides static constants and static methods for performing common calculations. The Math class is in the java.lang package, so it does not need to be imported.

63 The Math Class Constants
Two static constants PI - the value of pi E - the base of the natural logarithm Example: System.out.println( Math.PI ); System.out.println( Math.E ); The output is: See Example 3.13 MathConstants.java

64 Methods of the Math Class
All methods are static. See Example 3.14 MathMethods.java Return type Method name and argument list dataTypeOfArg abs( dataType arg ) returns the absolute value of the argument arg, which can be a double, float, int, or long. double log( double a ) returns the natural logarithm (in base e) of its argument. sqrt( double a ) returns the positive square root of a pow( double base, double exp ) returns the value of base raised to the power exp

65 The Math round Method Rounding rules:
Any factional part < .5 is rounded down Any fractional part .5 and above is rounded up See Example 3.15 MathRounding.java Return type Method name and argument list long round( double a ) returns the closest integer to its argument a

66 The Math min/max Methods
Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 ); See Example 3.16 MathMinMaxMethods.java Return type Method name and argument list dataTypeOfArgs min( dataType a, dataType b ) returns the smaller of the two arguments. The arguments can be doubles, floats, ints, or longs. max( dataType a, dataType b ) returns the larger of the two arguments. The arguments can be doubles, floats, ints, or longs.

67 The NumberFormat Class
The NumberFormat class (in the java.text package), like the DecimalFormat class, can be used to format numeric values for output. The NumberFormat class provides factory methods for creating currency and percentage objects that use predefined formatting patterns. These static factory methods are called instead of using instantiating an object using the new keyword.

68 The NumberFormat Class
See Example 3.17 DemoNumberFormat.java Return type Method name and argument list NumberFormat getCurrencyInstance( ) static method that creates an object for printing numbers as money getPercentInstance( ) static method that creates an object for printing percentages String format( double number ) returns a formatted String representation of number

69 The Wrapper Classes “Wrap" the value of a primitive data type into an object Useful when methods require an object argument Also useful for converting Strings to an int or double

70 Wrapper Classes Primitive Data Type Wrapper Class double Double float
long Long int Integer short Short byte Byte char Character boolean Boolean

71 Autoboxing and Unboxing
Automatic conversion between a primitive type and a wrapper object when a primitive type is used where an object is expected Integer intObject = 42; Unboxing Automatic conversion between a wrapper object and a primitive data type when a wrapper object is used where a primitive data type is expected int fortyTwo = intObject;

72 Integer and Double Methods
static Integer Methods static Double Methods See Example 3.18 DemoWrapper.java Return value Method Name and argument list int parseInt( String s ) returns the String s as an int Integer valueOf( String s ) returns the String s as an Integer object Return value Method Name and argument list double parseDouble( String s ) returns the String s as a double Double valueOf( String s ) returns the String s as a Double object

73 Using Dialog Boxes JOptionPane class is in the javax.swing package
static methods are provided for input and output dialog boxes For input dialog boxes, return value is a String, so numeric input needs to be converted (using parseInt or parseDouble)

74 JOptionPane static Methods
See Examples 3.19 DialogBoxDemo1.java Return value Method name and argument list String showInputDialog( Component parent, Object prompt ) pops up an input dialog box, where prompt asks the user for input. void showMessageDialog( Component parent, Object message ) pops up an output dialog box with message displayed

75 Reading Numeric Input The showInputDialog method returns a String.
To convert the String to a numeric type, use the wrapper class methods. Example: String input = JOptionPane.showInputDialog( null, "Please enter your age in years" ); int age = Integer.parseInt( input ); See Example 3.20 DialogBoxDemo2.java

76 Object-Oriented Programming Part 2: User-Defined Classes
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes

77 Topics Defining a Class Defining Instance Variables Writing Methods
The Object Reference this The toString and equals Methods static Members of a Class Graphical Objects enum Types Creating Packages Documentation Using Javadoc

78 Why User-Defined Classes?
Primitive data types (int, double, char, .. ) are great … … but in the real world, we deal with more complex objects: products, websites, flight records, employees, students, .. Object-oriented programming enables us to manipulate real-world objects.

79 User-Defined Classes Combine data and the methods that operate on the data Advantages: The class methods are responsible for the validity of the data. Implementation details can be hidden. A class can be reused. Client of a class A program that instantiates objects and calls the methods of the class

80 Syntax for Defining a Class
accessModifier class ClassName { // class definition goes here } ***Note that the curly braces are required.

81 Use a noun for the class name.
SOFTWARE ENGINEERING TIP Use a noun for the class name. Begin the class name with a capital letter.

82 Important Terminology
Fields instance variables: the data for each object class data: static data that all objects share Members fields and methods Access Modifier determines access rights for the class and its members defines where the class and its members can be used

83 Access Modifiers Access Modifier Class or member can be referenced by…
public methods of the same class and methods of other classes private methods of the same class only protected methods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package access) methods in the same package only

84 public vs. private Classes are usually declared to be public.
Instance variables are usually declared to be private. Methods that will be called by the client of the class are usually declared to be public. Methods that will be called only by other methods of the class are usually declared to be private. APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class.

85 Defining Instance Variables
Syntax: accessModifier dataType identifierList; dataType can be primitive data type or a class type identifierList can contain: one or more variable names of the same data type multiple variable names separated by commas initial values Optionally, instance variables can be declared as final.

86 Examples of Instance Variable Definitions
private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

87 SOFTWARE ENGINEERING TIP Define instance variables for the data that all objects will have in common. Define instance variables as private so that only the methods of the class will be able to set or change their values. Begin the instance variable identifier with a lowercase letter and capitalize internal words.

88 The Auto Class public class Auto { private String model; private int milesDriven; private double gallonsOfGas; } The Auto class has three instance variables: model, milesDriven, and gallonsOfGas.

89 Writing Methods Syntax:
accessModifier returnType methodName( parameter list ) // method header { // method body } parameter list is a comma-separated list of data types and variable names. to the client, these are arguments to the method, these are parameters The parentheses are required even if the method takes no parameters. **Note that the method header is the method’s API.

90 Use verbs for method names.
SOFTWARE ENGINEERING TIP Use verbs for method names. Begin the method name with a lowercase letter and capitalize internal words.

91 Method Return Types The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void. Methods with a return type of void do not return a value to the caller.

92 Method Body The code that performs the method's function is written between the beginning and ending curly braces. Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

93 main is a Method Let's look at main's API in detail:
public static void main( String [] args ) { // application code } Let's look at main's API in detail: public main can be called from outside the class. (The JVM calls main.) static main can be called by the JVM without instantiating an object. void main does not return a value String [] args main's parameter is a String array

94 Value-Returning Methods
Use a return statement to return a value Syntax: return expression; Note: All possible execution paths in the method must return a value. Thus, a method can have multiple return statements.

95 Constructors Special methods that are called automatically when an object is instantiated using the new keyword. A class can have several constructors. The job of the class constructors is to initialize the instance variables of the new object.

96 Defining a Constructor
Syntax: public ClassName( parameter list ) { // constructor body } Note: constructors have no return value, not even void! Each constructor must have a different number of parameters or parameters of different types. Default constructor: a constructor that takes no arguments. See Examples 7.1 and 7.2, Auto.java and AutoClient.java

97 Default Initial Values
If the constructor does not assign values to the instance variables, they receive default values depending on the instance variable’s data type. Data Type Default Value byte, short, int, long float, double 0.0 char The null character (\u0000) boolean false Any object reference (for example, a String) null

98 Common Error Trap Do not specify a return value for a constructor (not even void). Doing so will cause a compiler error in the client program when the client attempts to instantiate an object of the class.

99 Class Scope Instance variables have class scope, meaning that:
A constructor or method of a class can directly refer to instance variables. Methods also have class scope, meaning that: A constructor or method of a class can call other methods of a class (without using an object reference).

100 Local Scope A method's parameters have local scope, meaning that:
a method can directly access its parameters. but one method's parameters cannot be accessed by other methods. A method can define variables which also have local scope, meaning that: a method can access its local variables. but one method's local variables cannot be accessed by other methods.

101 Summary of Scope A method in a class can access:
the instance variables of its class any parameters sent to that method any variables that method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first any methods in the class

102 Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable)

103 Accessor Methods Example: the accessor method for model return model;
public String getModel( ) { return model; } See Examples 7.3 Auto.java and 7.4 AutoClient.java

104 Mutator Methods Mutator methods allow the client to change the values of instance variables. They have this general form: public void setInstanceVariable( dataType newValue ) { // if newValue is valid, // assign newValue to the instance variable }

105 Mutator Methods Example: the mutator method for milesDriven
public void setMilesDriven( int newMilesDriven ) { if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven; else System.err.println( "Miles driven " + "cannot be negative." ); System.err.println( "Value not changed." ); } See Examples 7.5 Auto.java and 7.6 AutoClient.java

106 SOFTWARE ENGINEERING TIP Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values. This eliminates duplicate code and makes the program easier to maintain.

107 Common Error Trap Do not declare method parameters.
Parameters are already defined and are assigned the values sent by the client to the method. Do not give the parameter the same name as an instance variable. The parameter has name precedence so it "hides" the instance variable. Do not declare a local variable with the same name as an instance variable. Local variables have name precedence and hide the instance variable.

108 Data Manipulation Methods
Perform the "business" of the class. Example: a method to calculate miles per gallon: public double calculateMilesPerGallon( ) { if ( gallonsOfGas != 0.0 ) return milesDriven / gallonsOfGas; else return 0.0; } See Examples 7.7 Auto.java and 7.8 AutoClient.java

109 The Object Reference this
How does a method know which object's data to use? this is an implicit parameter sent to methods. this is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied. Thus, variableName is understood to be this.variableName Example: model is understood to be this.model

110 Using this in a Mutator Method
public void setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Example: public void setModel( String model ) this.model = model; this.model refers to the instance variable. model refers to the parameter.

111 The toString Method Returns a String representing the data of an object Clients can call toString explicitly by coding the method call. Clients can call toString implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // instantiate // an object // explicit toString call System.out.println( compact.toString( ) ); // implicit toString call System.out.println( compact );

112 The toString API Return value Method name and argument list
returns a String representing the data of an object

113 Auto Class toString Method
public String toString( ) { DecimalFormat gallonsFormat = new DecimalFormat( "#0.0" ); return "Model: " + model + "; miles driven: " + milesDriven + "; gallons of gas: " + gallonsFormat.format( gallonsOfGas ); }

114 The equals Method Determines if the data in another object is equal to the data in this object. Example client code using Auto references auto1 and auto2: if ( auto1.equals( auto2 ) ) System.out.println( “The data in auto1 and " + "auto2 are the same." ); Return value Method name and argument list boolean equals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise.

115 The instanceof Operator
Because the equals method’s parameter is of type Object, we need to determine if the parameter is an Auto object. We can use the instanceof operator to determine if an object reference refers to an object of a particular class. Syntax: objectReference instanceof ClassName evaluates to true if objectReference is of ClassName type; false otherwise.

116 Auto Class equals Method
public boolean equals( Object o ) { // if o is not an Auto object, return false if ( ! ( o instanceof Auto ) ) return false; else // type cast o to an Auto object Auto objAuto = ( Auto ) o; if ( model.equals( objAuto.model ) && milesDriven == objAuto.milesDriven && Math.abs( gallonsOfGas - objAuto.gallonsOfGas ) < ) return true; } See Examples 7.10 Auto.java and 7.11 AutoClient.java

117 static Variables Also called class variables
One copy of a static variable is created per class. static variables are not associated with an object. static constants are often declared as public. To define static data, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName…; Example: private static int countAutos = 0;

118 static Methods Also called class methods
Often defined to access and change static variables static methods cannot access instance variables: static methods are associated with the class, not with any object. static methods do not have access to the implicit parameter this.

119 Rules for static and Non-static Methods
Access instance variables? no yes Access static class variables? Call static class methods? Call non-static instance methods? Use the object reference this? See Examples 7.12 Auto.java and 7.13 AutoClient.java

120 Reusable Graphical Objects
If our application draws an object, for example a Do Not Enter sign, we want to be able to separate the drawing of the object from the application. In this way, the Do Not Enter sign could be used by other applications.

121 The DoNotEnter Class To separate the Do Not Enter sign from the application, we define a DoNotEnter class. The starting x and y values become instance variables, along with a scaling factor to allow the client to draw signs of different sizes. We move the code for drawing the sign into a draw method, with this API: public void draw( Graphics g ) In this way, the logic for drawing the objects is encapsulated in the graphical object class. The client application calls the draw method from its paint method, passing the graphics context object.

122 The Client Application
The client instantiates DoNotEnter objects in its constructor, passing values for the starting x, y, and scale factor for each object. In the paint method, the client application calls the draw method for each DoNotEnter object. See Example 7.14 DoNotEnter.java, Example 7.15 DoNotEnterClient.java, and Example 7.16 DoNotEnterClient2.java.

123 enum Types Special class definition designed to increase the readability of code Allows you to define a set of objects that apply names to ordered sets Examples of ordered sets: Days of the week Months of the year Playing cards

124 enum Types Built into java.lang (no import statement needed) Syntax:
enum EnumName { obj1, obj2,… objn }; Example: enum Days { Sun, Mon, Tue, Wed, Thurs, Fri, Sat }; A constant object is instantiated for each name in the list. Thus, each name is a reference to an object of type Days.

125 Using an enum Object Referring to an enum object reference: Syntax:
EnumType.enumObject Example: Days.Mon Declaring an object reference of an enum type EnumType referenceName; Days d; // d is initially null d = Days.Thurs;

126 Useful enum Methods Return value Method name and argument list
int compareTo( Enum eObj ) compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are equal. ordinal( ) returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on.

127 More Useful enum Methods
Return value Method name and argument list boolean equals( Object eObj ) returns true if this object is equal to the argument eObj; returns false otherwise String toString( ) returns the name of the enum constant Enum valueOf( String enumName ) static method that returns the enum object whose name is the same as the String argument enumName See Example 7.17 EnumDemo.java

128 Using enum Objects with switch
Using enum objects for case constants makes the code more readable. For the case constant, use the enum object reference without the enum type Example: case Fri: See Example 7.18 DailySpecials.java

129 Creating Packages A package is a collection of related classes that can be imported into a program. Packages allow reuse of classes without needing to place the class in the same directory/folder as the other source files. To include a class in a package, precede the class definition with the package statement: package packageName;

130 Naming Packages To avoid name collisions, which can occur when multiple programmers define packages, we use this naming convention: Use the reverse of the domain name, excluding "www". For example, for a domain name: the package name would begin with: com.jbpub then add the package name: com.jbpub.af

131 A Reusable Class For example, we can create a class that provides type-safe reading of input from the console that can be reused by our programs. /** Type-Safe Input Using Scanner * Anderson, Franceschi */ package com.jbpub.af; // package name import java.util.Scanner; public class ConsoleIn { // rest of class definition See Example 7.20 ConsoleIn.java

132 Create the Folder Structure
For the package com.jbpub.af, we create three folders. We place the ConsoleIn.class into the af folder.

133 Modify the CLASSPATH The CLASSPATH environment variable tells the compiler where to look for packages. You will need to set the CLASSPATH to include the folder in which you created the com directory for your package. See your system documentation for how to set the CLASSPATH.

134 Client Use of Package To reuse a class in a package, the client imports the class. import com.jbpub.af.ConsoleIn; See Example 7.21 ConsoleInClient.java

135 Javadoc Documentation
The Java Class Library documentation on Oracle's website ( helps us determine how to instantiate objects and call methods for the classes. This documentation was generated using Javadoc, a tool provided in the Java Development Toolkit (JDK). We can use Javadoc to generate webpages that provide documentation on our class's fields and methods.

136 To Use Javadoc We need to add Javadoc comments and special tags to our classes. Javadoc comments begin with /** and end with */ (Note that this is similar to a Java block comment, but with an extra * in the opening syntax.) Example: /** Auto class * Anderson, Franceschi */

137 Block Tags Identify parameters and return values
HTML tags can be used in the descriptions For example, <BR /> to insert a new line Tag Common syntax @param @param variableName description @return @return description

138 Sample equals Method Documentation
/** * equals method:<BR /> * Compares the fields of two Auto objects a1 another object true if a1 is an Auto object and * this object’s fields have the same values * as a1’s fields; false, otherwise */ public boolean equals( Object a1 ) { // equals method body }

139 Executing Javadoc javadoc.exe is located in the bin directory of the Java JDK To generate documentation for a class: javadoc ClassName.java Example: javadoc Auto.java To generate documentation for all classes in a folder: javadoc *.java Many IDEs provide access to Javadoc. See Example 7.22 SimplifiedAuto.java

140 Sample Javadoc Documentation

141 Multidimensional Arrays and the ArrayList Class
Chapter 9 Multidimensional Arrays and the ArrayList Class

142 Topics Declaring and Instantiating Multidimensional Arrays
Aggregate Two-Dimensional Array Operations Other Multidimensional Arrays The ArrayList Class

143 Two-Dimensional Arrays
Allow organization of data in rows and columns in a table-like representation. Example: Daily temperatures can be arranged as 52 weeks with 7 days each.

144 Declaring Multidimensional Arrays
Declaring a two-dimensional array: datatype [][] arrayName; or datatype [][] arrayName1, arrayName2, …; Declaring a three-dimensional array: datatype [][][] arrayName; datatype [][][] arrayName1, arrayName2, …; Examples: double [][] dailyTemps, weeklyTemps; Auto [][][] cars;

145 Instantiating Multidimensional Arrays
Instantiating a two-dimensional array: arrayName = new datatype [exp1][exp2]; where exp1 and exp2 are expressions that evaluate to integers and specify, respectively, the number of rows and the number of columns in the array. Example: dailyTemps = new double [52][7]; dailyTemps has 52 rows and 7 columns, for a total of 364 elements.

146 Default Initial Values
When an array is instantiated, the array elements are given standard default values, identical to the default values of single-dimensional arrays: Array data type Default value byte, short, int, long float, double 0.0 char The null character (\u0000) boolean false Any object reference (for example, a String) null

147 Assigning Initial Values
datatype [][] arrayName = { { value00, value01, … }, { value10, value11, …}, … }; where valueMN is an expression that evaluates to the data type of the array and is the value to assign to the element at row M and column N. The number of sublists determines the number of rows in the array. The number of values in each sublist determines the number of columns in that row. Thus, a two-dimensional array can have a different number of columns in each row.

148 Assigning Initial Values Example
For example, this statement: int [][] numbersList1 = { { 0, 5, 10 }, { 0, 3, 6, 9 } }; instantiates this array:

149 An Array of Arrays As the preceding figure illustrates, a two-dimensional array is an array of arrays. The first dimension of a two-dimensional array is an array of array references, with each reference pointing to a single-dimensional array. Thus, a two-dimensional array is comprised of an array of rows, where each row is a single-dimensional array. It is possible that the rows of a two-dimensional array can have different lengths

150 Instantiating Arrays with Different-Length Rows
To instantiate a two-dimensional array whose rows have a different number of columns: 1. instantiate the two-dimensional array 2. instantiate each row as a single-dimensional array   //instantiate the array with 3 rows char [][] grades = new char [3][]; // instantiate each row   grades[0] = new char [23]; // instantiate row 0 grades[1] = new char [16]; // instantiate row 1 grades[2] = new char [12]; // instantiate row 2

151 Accessing Array Elements
Elements of a two-dimensional array are accessed using this syntax: arrayName[exp1][exp2] exp1 is the element's row index. row index of the first row: 0 row index of last row: number of rows - 1 exp2 is the element's column index. column index of first column: 0 column index of last column: number of columns in that row - 1

152 The Length of the Array The number of rows in a two-dimensional array is: arrayName.length The number of columns in row n in a two-dimensional array is: arrayName[n].length

153 Accessing Two-Dimensional Array Elements
Syntax Row 0, column j arrayName[0][j] Row i, column j arrayName[i][j] Last row, column j arrayName[arrayName.length – 1][j] Last row, last column arrayName[arrayName.length – 1] [arrayName [arrayName.length -1].length – 1] Number of rows arrayName.length Number of columns in row i arrayName[i].length

154 Example: Family Cell Bills
We want to analyze three months of cell phone bills for a family of four: See Example 9.1 FamilyCellBills.java

155 Example: 2-D Array of Autos
Auto sedan1 = new Auto( "BMW", 0, 0.0 ); Auto sedan2 = new Auto( "BMW", 100, 15.0 ); Auto sedan3 = new Auto( "Toyota", 0, 0.0 ); Auto sportsCar = new Auto( "Ferrari", 0, 0.0 ); // declare and initialize 2-D array of Autos Auto [ ][ ] cars = { { sedan1, sedan2, sedan3 }, { sportsCar, new Auto( ) } }; Auto retrievedCar = cars[1][0]; // retrievedCar gets the sportsCar object reference System.out.println( "cars[1][0]'s model is: " + retrievedCar.getModel( ) ); See Example 9.2 TwoDimAutoArray.java

156 Aggregate Array Operations
To process all array elements in row order, we use a nested for loop: for ( int i = 0; i < arrayName.length; i++ ) { for ( int j = 0; j < arrayName[i].length; j++ ) // process element arrayName[i][j] } The outer loop processes the rows. The inner loop processes the columns within each row. See Example 9.3 OutputFamilyCellBills.java

157 Processing a Given Row If we want to find the maximum bill for a particular month or the total bills for a month, we need to process just one row. To process just row i, we use this standard form: for ( int j = 0; j < arrayName[i].length; j++ ) { // process element arrayName[i][j] } See Example 9.4 SumRowFamilyCellBills.java

158 Processing a Given Column
If we want to determine the highest cell bill for one person, we need to process just one column. To process just column j, we use this standard form: for ( int i = 0; i < arrayName.length; i++ ) { if ( j < arrayName[i].length ) // process element arrayName[i][j] } Note: Because rows have variable lengths, we must verify that the current row has a column j before attempting to process the element. See Example 9.5 MaxMemberBill.java

159 Processing One Row at a Time
If we want to determine the total of the cell bills for each month, we need to process all rows, calculating a total at the end of each row. We use this standard form: for ( int i = 0; i < arrayName.length; i++ ) { // initialize processing variables for row i for ( int j = 0; j < arrayName[i].length; j++ ) // process element arrayName[i][j] } // end inner for loop // finish the processing of row i } // end outer for loop See Example 9.6 SumEachRowFamilyCellBills.java

160 Common Error Trap Failing to initialize the row processing variables before processing each row is a logic error and will generate incorrect results.

161 Processing A Column at a Time
Suppose we want to process test grades for three courses. Each course has a different number of tests, so each row has a different number of columns: int [][] grades = { { 89, 75 }, { 84, 76, 92, 96 }, { 80, 88, 95 } }; First, we need to find the number of columns in the largest row. We use that in our loop condition. Then before attempting to process the array element, we check whether the given column exists in the current row.

162 Processing A Column at a Time (con't)
We have stored the maximum number of columns in maxNumberOfColumns; the general pattern for processing elements one column at a time is: for ( int j = 0; j < maxNumberOfColumns; j++ ) { for ( int i = 0; i < arrayName.length; i++ ) // does column j exist in this row? if ( j < arrayName[i].length ) // process element arrayName[i][j] } See Example 9.7 GradesProcessing.java

163 Two-Dimensional Arrays Passed to and Returned from Methods
The syntax for a method that accepts a 2-D array as a parameter is the following: returnType methodName( arrayType [][] arrayParameterName ) The syntax for a method that returns a 2-D array is the following: returnArrayType [][] methodName( paramList ) The caller of the method passes the argument list and assigns the return value to a reference to a 2-D array of the appropriate data type. See Examples 9.9 Tally.java and 9.10 VoteTally.java

164 Displaying Array Data as a Bar Chart
We use our standard nested for loops. We call the fillRect method of the Graphics class for the bars and the drawString method to print each element's value. To change colors for each row, we use an array of Color objects, and loop through the array to set the color for each row. Each time we process a row, we reset the x and y values for the first bar. See Example 9.8 FamilyBarChart.java

165 Other Multidimensional Arrays
If we want to keep track of sales on a per-year, per-week, and per-day basis, we could use a three-dimensional array:  1st dimension: year 2nd dimension: week 3rd dimension: day of the week

166 Sample Code // declare a three-dimensional array double [][][] sales;
// instantiate the array for 10 years, 52 weeks, // and 7 days sales = new double [10][52][7]; // set the value of the first element sales[0][0][0] = ; // set the value for year 5, week 23, day 4 sales [4][22][3] = ; // set the last value in the array sales [9][51][6] = ;

167 Structure of an n-Dimensional Array
Array Element first arrayName[i1] is an (n-1)-dimensional array second arrayName[i1][i2] is an (n-2)-dimensional array kth arrayName[i1][i2][i3][..][ik] is an (n-k)-dimensional array (n-1)th arrayName[i1][i2][i3][..][in-1] is a single-dimensional array nth arrayName[i1][i2][i3][..][in-1][in] is an array element

168 General Pattern for Processing a Three-Dimensional Array
for ( int i = 0; i < arrayName.length; i++ ) { for ( int j = 0; j < arrayName[i].length; j++ ) for ( int k = 0; k < arrayName[i][j].length; k++ ) // process the element arrayName[i][j][k] }

169 Code to Print the sales Array
for ( int i = 0; i < sales.length; i++ ) { for ( int j = 0; j < sales[i].length; j++ ) for ( int k = 0; k < sales[i][j].length; k++ ) // print the element at sales[i][j][k] System.out.print( sales[i][j][k] + "\t" ); } // skip a line after each week System.out.println( ); // skip a line after each month System.out.println( );

170 A Four-Dimensional Array
If we want to keep track of sales on a per-state, per-year, per-week, and per-day basis, we could use a four-dimensional array:  1st dimension: state 2nd dimension: year 3rd dimension: week 4th dimension: day of the week double[][][][] sales = new double [50][10][52][7];

171 General Pattern for Processing a Four-Dimensional Array
for ( int i = 0; i < arrayName.length; i++ ) { for ( int j = 0; j < arrayName[i].length; j++ ) for ( int k = 0; k < arrayName[i][j].length; k++ ) for ( int l = 0; l < arrayName[i][j][k].length; l++ ) // process element arrayName[i][j][k][l] }

172 The ArrayList Class Arrays have a fixed size after they have been instantiated. What if we don't know how many elements we will need? For example, if we are reading values from a file returning search results We could create a very large array, but then we waste space for all unused elements. A better idea is to use an ArrayList, which stores elements of object references and automatically expands its size, as needed.

173 The ArrayList Class The ArrayList class is in the package: java.util
All ArrayList elements are object references, so we could have an ArrayList of Auto objects, Book objects, Strings, etc. To store primitive types in an ArrayList, use the wrapper classes (Integer, Double, Character, Boolean, etc.) The ArrayList is a generic class. The ArrayList class has been written so that it can store object references of any type specified by the client.

174 Declaring an ArrayList
Use this syntax: ArrayList<E> arrayListName; E is a class name that specifies the type of object references that will be stored in the ArrayList. Example: ArrayList<String> listOfStrings; ArrayList<Auto> listOfCars; ArrayList<Integer> listOfInts;

175 ArrayList Constructors
The capacity of an ArrayList is the total number of elements allocated to the list. The size of an an ArrayList is the number of elements that are used. Constructor name and argument list ArrayList<E>( ) constructs an ArrayList object of type E with an initial capacity of 10 ArrayList<E>( int initialCapacity ) constructs an ArrayList object of type E with the specified initial capacity

176 Instantiating an ArrayList
This list has a capacity of 10 Auto references, but a size of 0. ArrayList<Auto> listOfAutos = new ArrayList<Auto>( ); This list has a capacity of 5 Strings, but a size of 0. ArrayList<String> listOfStrings = new ArrayList<String>( 5 );

177 ArrayList Methods Return value Method name and argument list boolean
add( E element ) appends element to the end of the list E remove( int index ) removes and returns the element at the specified index position void clear( ) removes all the elements in the list int size( ) returns the number of elements in the list

178 More ArrayList Methods
Return value Method name and argument list E get( int index ) returns the element at the specified index position; the element is not removed from the list. set( int index, E element ) replaces the current element at the specified index position with the specified element and returns the replaced element. void trimToSize( ) sets the capacity of the list to its current size.

179 Processing Array Lists
Using a standard for loop: ClassName currentObject; for ( int i = 0; i < arrayListName.size( ); i++ ) { currentObject = arrayListName.get( i ); // process currentObject } Example: Auto currentAuto; for ( int i = 0; i < listOfAutos.size( ); i++ ) currentAuto = listOfAutos.get( i ); // process currentAuto

180 The Enhanced for Loop Simplifies processing of lists.
The standard form is: for ( ClassName currentObject : arrayListName ) { // process currentObject } This enhanced for loop prints all elements of an ArrayList of Strings named list: for ( String s : list ) System.out.println( s ); See Example 9.12 ArrayListOfIntegers.java

181 Using an ArrayList We want to write a program for a bookstore that allows users to search for books using keywords. We will have three classes in this program: A Book class, with instance variables representing the title, author, and price A BookStore class that stores Book objects in an ArrayList and provides a searchForTitle method A BookSearchEngine class that provides the user interface and the main method See Example 9.13 Book.java Example BookStore.java and Example 9.15 BookSearchEngine.java

182 Chapter 10 Object-Oriented Programming Part 3:
Inheritance, Polymorphism, and Interfaces

183 Topics Inheritance Concepts Inheritance Design
Inherited Members of a Class Subclass Constructors Adding Specialization to the Subclass Overriding Inherited Methods The protected Access Modifier abstract Classes and Methods Polymorphism Interfaces

184 Inheritance Concepts A common form of reuse of classes is inheritance.
We can organize classes into hierarchies of functionality. The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy. We derive a subclass, which inherits behavior and fields from the superclass.

185 A Sample Vehicle Hierarchy
This hierarchy is depicted using a Unified Modeling Language (UML) diagram. In UML diagrams, arrows point from the subclass to the superclass.

186 Superclasses and Subclasses
A superclass can have multiple subclasses. Subclasses can be superclasses of other subclasses. A subclass can inherit directly from only one superclass. All classes inherit from the Object class.

187 Superclasses and Subclasses
A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses. A subclass can define new instance variables and methods, some of which may override (hide) those of a superclass.

188 Specifying Inheritance
The syntax for defining a subclass is to use the extends keyword in the class header, as in accessModifier class SubclassName extends SuperclassName { // class definition } The superclass name specified after the extends keyword is called the direct superclass. As mentioned, a subclass can have many superclasses, but only one direct superclass.

189 An Application Hierarchy
When we wrote a graphical application, we defined a subclass of JFrame. We say that inheritance implements an "is a" relationship, in that a subclass object is a superclass object as well. Thus, RollABall "is a" JFrame (its direct superclass), a Frame, a Window, a Container, a Component, and an Object. RollABall begins with more than 360 methods and 28 fields inherited from its 6 superclasses.

190 The BankAccount Hierarchy

191 The BankAccount Class The BankAccount class is the superclass.
Instance variables: balance (double) MONEY (a public constant DecimalFormat object) Methods: Default and overloaded constructors deposit and withdraw methods balance accessor toString See Example 10.1 BankAccount.java

192 The CheckingAccount Class
We derive the CheckingAccount subclass from BankAccount: public class CheckingAccount extends BankAccount { } A subclass inherits the public members of a superclass (except constructors). Thus, the CheckingAccount class inherits the MONEY instance variable The getBalance, deposit, withdraw, and toString methods See Example 10.2 CheckingAccount.java And Example 10.3 CheckingAccountClient.java

193 private Members Superclass members declared as private are not inherited, although they are part of the subclass. Thus, a balance instance variable is allocated to all CheckingAccount objects, but methods of the CheckingAccount class cannot directly access balance. To set or get the value of balance, the CheckingAccount methods must call the inherited withdraw, deposit, or getBalance methods. This simplifies maintenance because the BankAccount class enforces the data validation rules for balance.

194 protected Members protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass. Disadvantage: Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. For that reason, we prefer to use private, rather than protected, for our instance variables.

195 Inheritance Rules Superclass Members Inherited by subclass?
Directly Accessible by Subclass? Directly Accessible by Client of Subclass? public fields yes yes, by using field name public methods yes, by calling method from subclass methods protected fields no, must call accessors and mutators protected methods no private fields private methods

196 Subclass Constructors
Constructors are not inherited. However, the subclass can and should call the constructors of the superclass to initialize inherited fields. Implicit invocation The default constructor of the subclass automatically calls the default constructor of the superclass For explicit invocation, use this syntax: super( argument list ); If used, this statement must be the first statement in the subclass constructor

197 CheckingAccount Constructors
public CheckingAccount( ) { // optional explicit call // to BankAccount default constructor super( ); } public CheckingAccount( double startBalance ) // explicit call to BankAccount // overloaded constructor super( startBalance ); See Examples 10.4 , 10.5, and 10.6

198 Common Error Trap An attempt by a subclass to directly access a private field or call a private method defined in a superclass will generate a compiler error. To set initial values for private variables, call the appropriate constructor of the direct superclass. For example, this statement in the overloaded CheckingAccount class constructor calls the overloaded constructor of the BankAccount class: super( startBalance );

199 SOFTWARE ENGINEERING TIP An overloaded constructor in a subclass should explicitly call a direct superclass constructor to initialize the fields in its superclass.

200 Inheritance Rules for Constructors
Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass Using a Subclass Reference? constructors no yes, using super( arg list ) in a subclass constructor

201 Adding Specialization
A subclass can define new fields and methods. Our CheckingAccount class adds these instance variables: monthlyFee, a double DEFAULT_FEE, a double constant these methods: getMonthlyFee, the accessor setMonthlyFee, the mutator applyMonthlyFee, which charges the monthly fee to the account.

202 The applyMonthlyFee Method
Because balance is private in the BankAccount class, the applyMonthlyFee method calls the withdraw method to subtract the monthly fee from the balance: public void applyMonthlyFee( ) { withdraw( monthlyFee ); } See Examples 10.7 and 10.8

203 SOFTWARE ENGINEERING TIP The superclasses in a class hierarchy should define fields and methods common to all subclasses. The subclasses should add specialized fields and methods.

204 Overriding Inherited Methods
A subclass can override (or replace) an inherited method by providing a new version of the method. The API of the new version must match the inherited method. When the client calls the method, it will call the subclass version. Overridden superclass methods are invisible to the client of the subclass, but the subclass methods can still call a superclass method using this syntax: super.methodName( argument list )

205 The toString Method The toString method in the CheckingAccount class overrides the toString method in the BankAccount class. The subclass version calls the superclass version to return balance. public String toString( ) { return super.toString( ) + "; monthly fee is " + MONEY.format( monthlyFee ); } See Examples 10.9 and 10.10

206 Inheritance Rules for Overridden Methods
Superclass Members Inherited by Subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass Using a Subclass Reference? public or protected inherited methods that have been overridden in the subclass no yes, using super.methodName( arg list )

207 Common Error Trap Do not confuse overriding a method with overloading a method. Overriding a method: A subclass provides a new version of that method (same signature/same name and argument list), which hides the superclass version from the client. Overloading a method: A class provides another version of the method, which varies in the number and/or type of parameters (different signature/same name and different argument list). A client of the class can call any of the public versions of overloaded methods.

208 The protected Access Modifier
Declaring fields as private preserves encapsulation. Subclass methods call superclass methods to set the values of the fields, and the superclass methods enforce the validation rules for the data. But calling methods incurs processing overhead. Declaring fields as protected allows them to be accessed directly by subclass methods. Classes outside the hierarchy and package must use accessors and mutators for protected fields.

209 Tradeoffs for protected Fields
Advantage: protected fields can be accessed directly by subclasses, so there is no method-invocation overhead. Disadvantage: Maintenance is complicated because the subclass also needs to enforce validation rules. Recommendation: Define protected fields only when high performance is necessary. Avoid directly setting the values of protected fields in the subclass. See Examples 10.11, 10.12, and 10.13

210 abstract Classes and Methods
An abstract class is a class that is not completely implemented. Usually, the abstract class contains at least one abstract method. An abstract method specifies an API but does not provide an implementation. The abstract method is used as a pattern for a method the subclasses should implement.

211 More on abstract Classes
An abstract class cannot be used to instantiate objects (because the class is not complete). However, an object reference to an abstract class can be declared. We use this capability in polymorphism, discussed later. An abstract class can be extended. subclasses can complete the implementation. Objects of those subclasses can be instantiated.

212 Defining an abstract Class
To declare a class as abstract, include the abstract keyword in the class header: accessModifier abstract class ClassName { // class body }

213 Defining an abstract Method
To declare a method as abstract, include the abstract keyword in the method header, and end the header with a semicolon: accessModifier abstract returnType methodName( argument list ); Note: The semicolon at the end of the header indicates that the method has no code. We do not use opening and closing curly braces { }

214 Example Figure Hierarchy
Figure is the abstract superclass. (Shown in UML in italics) Circle and Square are non-abstract subclasses

215 The Figure Class public abstract class Figure { private int x; private int y; private Color color; // usual constructors, accessors, // and mutators // abstract draw method public abstract void draw( Graphics g ); } All classes in the hierarchy will have an (x, y) coordinate and color. Subclasses will implement the draw method.

216 Subclasses of abstract Classes
A subclass of an abstract class can implement all, some, or none of the abstract methods. If the subclass does not implement all of the abstract methods, it must also be declared as abstract. Our Circle subclass adds a radius instance variable and implements the draw method. Our Square subclass adds a length instance variable and implements the draw method. See Examples 10.15, 10.16, 10.17, and 10.18

217 Using abstract Classes
Classes must be declared abstract if the class contains any abstract methods. abstract classes can be extended. abstract classes cannot be used to instantiate objects. An object reference to an abstract class can be declared.

218 Restrictions for Defining abstract Methods
abstract methods can be declared only within an abstract class. An abstract method must consist of a method header followed by a semicolon. abstract methods cannot be called. abstract methods cannot be declared as private or static. A constructor cannot be declared abstract.

219 Polymorphism An important concept in inheritance is that an object of a subclass is also an object of any of its superclasses. That concept is the basis for an important OOP feature, called polymorphism. Polymorphism simplifies the processing of various objects in the same class hierarchy because we can use the same method call for any object in the hierarchy using a superclass object reference.

220 Polymorphism Requirements
To use polymorphism, these conditions must be true: the classes are in the same hierarchy. all subclasses override the same method. a subclass object reference is assigned to a superclass object reference. the superclass object reference is used to call the overridden method.

221 Example Example shows how we can simplify the drawing of Circle and Square objects. We instantiate a Figure ArrayList and add Circle and Square objects to it. ArrayList<Figure> figuresList = new ArrayList<Figure>( ); figuresList.add( new Square( 150, 100, Color.BLACK, 40 ) ); figuresList.add( new Circle( 160, 110, Color.RED, 10 ) ); In the paint method, we call draw for each Figure: for ( Figure f : figuresList ) f.draw( g );

222 Polymorphism Conditions
Example shows that we have fulfilled the conditions for polymorphism: The Figure, Circle, and Square classes are in the same hierarchy. The non-abstract Circle and Square classes implement the draw method. We assigned the Circle and Square objects to Figure references. We called the draw method using Figure references.

223 Interfaces A class can inherit directly from only one class, that is, a class can extend only one class. To allow a class to inherit behavior from multiple sources, Java provides the interface. An interface typically specifies behavior that a class will implement. Interface members can be any of the following: ·   classes ·   constants ·   abstract methods ·   other interfaces

224 Interface Syntax To define an interface, use the following syntax:
accessModifier interface InterfaceName { // body of interface } All interfaces are abstract; thus, they cannot be instantiated. The abstract keyword, however, can be omitted in the interface definition.

225 Finer Points of Interfaces
An interface's fields are public, static, and final. These keywords can be specified or omitted. When you define a field in an interface, you must assign a value to the field.  All methods within an interface must be abstract, so the method definition must consist of only a method header and a semicolon. The abstract keyword also can be omitted from the method definition.

226 Inheriting from an Interface
To inherit from an interface, a class declares that it implements the interface in the class definition, using the following syntax:   accessModifier class ClassName extends SuperclassName implements Interface1, Interface2, … The extends clause is optional. A class can implement 0, 1, or more interfaces. When a class implements an interface, the class must provide an implementation for each method in the interface.

227 String Parsing Example
We define a StringHandler interface for use in parsing Strings. public interface StringHandler { public void processLetter( char c ); public void processDigit( char c ); public void processOther( char c ); } This interface is implemented by both a PasswordSecurityHandler class and a HexStringHandler class.

228 A Second Interface We also define a validator interface:
public interface Validator { public boolean isValid( ); } The HexStringHandler implements this interface in addition to the StringHandler interface. See Examples 10.21, 10.22, 10.23, & 10.24

229 The UML for the Example The filled diamond in UML means composition, expressed as “has a”. In this case, the StringParser class has a StringHandler. See Examples – 10.27

230 Exceptions and Input/Output Operations
Chapter 11 Exceptions and Input/Output Operations

231 Topics Exception Handling Using try and catch Blocks
Catching Multiple Exceptions User-Defined Exceptions The java.io Package Reading Text Files Using Scanner Writing and Appending to Text Files Parsing a String using Scanner Reading Structured Text Files Reading and Writing Objects to a File

232 Exceptions Illegal operations at run time can generate an exception.
For example, we have seen these exceptions: ArithmeticException NullPointerException InputMismatchException NumberFormatException ArrayIndexOutOfBoundsException

233 Handling Exceptions In a program without a Graphical User Interface, exceptions cause the program to terminate. With this code that attempts to read an int: String s = JOptionPane.showInputDialog( null, "Enter an integer" ); int n = Integer.parseInt( s ); If the user enters a, we get a NumberFormatException: See Example 11.1 DialogBoxInput.java You entered a Exception in thread “main” java.lang.NumberFormatException: For input string: “a” at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at DialogBoxInput.main(DialogBoxInput.java:17)

234 Handling Exceptions We don't want invalid user input to terminate our programs! It is better to detect the problem and reprompt the user for the input. Java allows us to intercept and handle some of these exceptions using try and catch blocks. Inside the try block, we put the code that might generate an exception. Inside catch blocks, we put the code to handle any exceptions that could be generated.

235 Minimum try/catch Syntax
{ // code that might generate an exception } catch( ExceptionClass exceptionObjRef ) // code to recover from the exception If an exception occurs in the try block, control jumps immediately to the catch block. No further instructions in the try block are executed. If no exceptions are generated in the try block, the catch block is not executed.

236 Exception Class Hierarchy
The Exception class, RuntimeException class, and their subclasses are in the java.lang package The ExceptionClass parameter to the catch block can be any of these exceptions. The IOException class and its subclasses are in the java.io package.

237 Checked and Unchecked Exceptions
Java distinguishes between two types of exceptions: Unchecked exceptions are those that are subclasses of Error or RuntimeException It is not mandatory to use try and catch blocks to handle these exceptions. Checked exceptions are any other exceptions. Code that might generate a checked exception must be put inside a try block or the method containing the code must acknowledge that the exception may occur by using a throws clause in the method header. Otherwise, the compiler will generate an error.

238 Exception Class Methods
Inside the catch block, you can call any of these methods of the Exception class: Return value Method name and argument list String getMessage( ) returns a message indicating the cause of the exception toString( ) returns a String containing the exception class name and a message indicating the cause of the exception void printStackTrace( ) prints the line number of the code that caused the exception along with the sequence of method calls leading up to the exception

239 Catching a NumberFormatException
int n = 0; // declare and initialize variable String s = JOptionPane.showInputDialog( null, "Enter an integer" ); try { n = Integer.parseInt( s ); System.out.println( "You entered " + n ); } catch ( NumberFormatException nfe ) System.out.println( "Incompatible data." ); See Example 11.2 DialogBoxInput.java

240 Initializing Variables for try/catch
Notice that we declare and initialize the input variable (n) before we enter the try block. If we do not initialize the variable and then try to access it after the try/catch blocks, we will receive the following compiler error: variable n might not have been initialized  The error indicates that the only place where n is assigned a value is in the try block. If an exception occurs, the try block will be interrupted and we might not ever assign n a value. Initializing the value before entering the try block solves this problem.

241 Recovering From an Exception
The previous code simply printed a message when the exception occurred. To continue processing, reprompt the user for good input by putting the try and catch blocks inside a do/while loop, as shown on the next slide. See Example 11.3 DialogBoxInput.java

242 int n = 0; boolean goodInput = false; // flag variable String s = JOptionPane.showInputDialog( null, "Enter an integer" ); do { try n = Integer.parseInt( s ); goodInput = true; // executed if no exception } catch ( NumberFormatException nfe ) s = JOptionPane.showInputDialog( null, s + " is not an integer. " + "Enter an integer" ); } while ( ! goodInput );

243 Always try to write code that is user-friendly.
SOFTWARE ENGINEERING TIP Write code to catch and handle exceptions generated by invalid user input. Always try to write code that is user-friendly. Although the methods of the Exception class are good debugging tools, they are not necessarily appropriate to use in the final version of a program.

244 Catching Multiple Exceptions
If the code in the try block might generate multiple, different exceptions, we can provide multiple catch blocks to handle each possible exception. When an exception is generated, the JVM searches the catch blocks in order. The first catch block with a parameter that matches the exception thrown will execute; any remaining catch blocks will be skipped.

245 catch Block Order An exception will match a catch block with a parameter that names any of its superclasses. For example, a NumberFormatException will match a catch block with a RuntimeException parameter. All exceptions will match a catch block with an Exception parameter. Thus, when coding several catch blocks, arrange the catch blocks with the specialized exceptions first, followed by more general exceptions.

246 The finally Block Optionally, you can follow the catch blocks with a finally block. The finally block will be executed whether or not an exception occurs. Thus: if an exception occurs, the finally block will be executed when the appropriate catch block finishes executing. if no exception occurs, the finally block will be executed when the try block finishes. For example, a finally block might be used to close an open file. We demonstrate this later.

247 Full try/catch/finally Syntax
{ // code that might generate an exception } catch( Exception1Class e1 ) // code to handle an Exception1Class exception catch( ExceptionNClass eN ) // code to handle an ExceptionNClass exception finally // code to execute whether or not an exception occurs Full try/catch/finally Syntax

248 Catching Multiple Exceptions
We can write a program that catches several exceptions. For example, for a division operation, we can prompt the user for a divisor. If the input is not an integer, we catch the NumberFormatException and reprompt the user with an appropriate message. If the input is 0, we catch an ArithmeticException when we attempt to divide by 0, and reprompt the user with an appropriate message. See Example 11.4 Divider.java

249 User-Defined Exceptions
We can design our own exception class. Suppose we want to design a class encapsulating addresses ( Address class). For simplicity, we say that a legal address is a String containing character. Our Address constructor will throw an exception if its address argument is illegal.   To do this, we design an exception class named Illegal Exception.

250 User-Defined Exception
Java has an IllegalArgumentException class, so our Illegal Exception class can be a subclass of the IllegalArgumentException class. By extending the IllegalArgumentException class: we inherit the functionality of an exception class, which simplifies our coding of the exception we can easily associate a specific error message with the exception

251 Extending an Existing Exception
We need to code only the constructor, which accepts the error message as a String. General pattern: public class ExceptionName extends ExistingExceptionClassName { public ExceptionName( String message ) super( message ); } See Example 11.5 Illegal Exception.java

252 Throwing an Exception The pattern for a method that throws a user-defined exception is:   accessModifier returnType methodName( parameters ) throws ExceptionName { if ( parameter list is legal ) process the parameter list else throw new ExceptionName( "Message here" ); } The message passed to the constructor identifies the error detected. In a client's catch block, the getMessage method retrieves that message. See Examples Address.java & Checker.java

253 Selected Input Classes in the java.io Package
Description InputStream Abstract superclass representing a stream of raw bytes FileInputStream Input stream to read raw bytes of data from files ObjectInputStream Class to read/recover objects from a file written using ObjectOutputStream

254 Hierarchy for Input Classes

255 Selected java.io Output Classes
Description Writer Abstract superclass for output classes OutputStream Abstract superclass representing an output stream of raw bytes PrintWriter Prints basic data types, Strings, and objects FileOutputStream Output stream for writing raw bytes of data to files ObjectOutputStream Class to write objects to a file

256 Hierarchy for Output Classes
These output classes are in the java.io package.

257 Reading from a File Java supports two file types:
text: data is stored as characters binary: data is stored as raw bytes. The type of a file is determined when the file is written to and depends on which classes were used to write to the file. Thus, to read from an existing file, you must know the file’s type in order to select the appropriate classes. We concentrate first on text files.

258 Reading Text Files Using Scanner
To read a text file we associate a Scanner object with a File object. Example: Scanner file = new Scanner( new File( "filename.txt" ) ); File Constructor Exceptions Thrown File( String pathname ) Constructs a File object with the pathname file name so that the file name is platform-independent. NullPointerException Scanner Constructor Scanner( File file ) Constructs a Scanner object for reading from a file. FileNotFoundException

259 Scanner Method APIs These methods test for remaining input in the file. Return value Method name and argument list Exceptions thrown boolean hasNext( ) returns true if there is another token in the Scanner object IllegalStateException hasNextLine( ) returns true if there is another line or line separator in the Scanner object hasNextInt( ) hasNextDouble( ) returns true if there is another token in the Scanner object of the specified data type.

260 More Scanner Method APIs
These methods read input from the file. Return value Method name and argument list Exceptions thrown String next( ) returns the next token IllegalStateException NoSuchElementException nextLine( ) returns the remainder of the line. Positions the file pointer to the next line. int double nextInt( ) nextDouble( ) returns the next token in the Scanner object as the specified data type. InputMismatchException

261 Opening and Closing an Input or Output Stream
When we construct an input stream or output stream object, the JVM associates the file name, standard input stream, or standard output stream with our object. This is opening the file. When we are finished with a file, we call the close method to release the resources associated with the file. Example: file.close( ); Return value Method name and argument list void close( ) releases resources associated with an open input stream.

262 Opening and Closing Standard Streams
The standard input stream (System.in), the standard output stream (System.out), and the standard error stream (System.err) are open when the program begins. They are intended to stay open and should not be closed.

263 SOFTWARE ENGINEERING TIP Calling the close method is optional. When the program finishes executing, all the resources of any unclosed files are released. It is good practice to call the close method, however, especially if you will be opening a number of files (or opening the same file multiple times.) Do not close the standard input, output, or error devices, however. They are intended to remain open.

264 Exceptions While Reading from a File
FileNotFoundException thrown by the Scanner constructor if the filename is not found InputMismatchException thrown by Scanner next…methods that read a numeric data type if the next token does not match the expected data type. NoSuchElementException thrown by Scanner methods if we attempt to read beyond the end of the file. IllegalStateException thrown by Scanner methods if we attempt to read after calling the close method. See Example 11.8 ClassicMovies.java

265 Scanner nextLine Method
The Scanner nextLine method works differently from the other Scanner next… methods. nextLine method reads any part of the line that has not already been read, including the newline character (which is not returned). nextInt, nextDouble, etc read only the next token on the line, stopping when trailing white space (such as a newline) is encountered and leaving the newline character and any trailing white space in the input stream. See Example 11.8 ClassicMovies.java for a demonstration of handling this different functionality.

266 Writing to Text Files Several situations can exist:
the file does not exist the file exists and we want to replace the current contents the file exists and we want to append to the current contents We specify whether we want to replace the contents or append to the current contents when we construct our FileOutputStream object.

267 Constructors for Writing to Text Files
Class Constructor FileOutputStream FileOutputStream( String filename, boolean mode ) constructs a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. PrintWriter PrintWriter( OutputStream os ) constructs a PrintWriter object from an OutputStream object

268 Methods of the PrintWriter Class
See Example 11.9 WriteGradeFile.java and Example AppendGradeFile.java Return value Method name and argument list void Void print( int i ) print( double d ) print( String s ) println( int i ) println( double d ) println( String s ) writes the argument to the text file close( ) releases resources allocated to the PrintWriter object.

269 Reading Structured Text Files
Some text files are organized into lines that represent a record — a set of data values containing information about an item. The data values are separated by one or more delimiters; that is, a special character or characters that separate one value from the next. As we read the file, we need to parse each line; that is, separate the line into the individual data values called tokens.

270 Example An airline company could store data in a file where each line represents a flight segment containing the following data: flight number origin airport destination airport number of passengers average ticket price  Such a file could contain the following data: AA123,BWI,SFO,235,239.5 AA200,BOS,JFK,150,89.3 In this case, the delimiter is a comma.

271 Using Scanner to Parse Strings
The Scanner constructor below accepts a String. We can use any of the Scanner next methods to read tokens from the String. We can use any of the Scanner hasNext methods to determine whether more tokens are available to be read. The default delimiters are the white space characters (space, newline, tab, etc.). Constructor name and argument list Scanner( String source ) constructs a Scanner object that produces tokens from the specified String

272 Using Scanner to Parse Strings
To specify different delimiters, call the useDelimiter method: Here, pattern represents a regular expression against which to match sequences of characters using standard characters as well as meta-characters, which have special meanings. We can specify a delimiter consisting of a single character or multiple specific characters as a simple String argument. See Example UsingScannerToParseAString.java Return Value Method name and argument list Scanner useDelimiter( String pattern ) sets the delimiter to pattern and returns this Scanner object.

273 Example The file flight.txt contains the following comma-separated flight data on each line: flight number, origin airport, destination airport, number of passengers, average ticket price The FlightRecord class defines instance variables for each flight data value The ReadFlights class reads data from flights.txt, instantiates FlightRecord objects, and adds them to an ArrayList. See Examples FlightRecord.java and Example ReadFlights.java

274 Reading and Writing Objects
Java also supports writing objects to a file and reading them as objects. This is convenient for two reasons:  We can write these objects directly to a file without having to convert the objects to primitive data types or Strings. We can read the objects directly from a file, without having to read Strings and convert these Strings to primitive data types in order to instantiate objects.   To read objects from a file, the objects must have been written to that file as objects.

275 Writing Objects to a File
To write an object to a file, its class must implement the Serializable interface, which indicates that: the object can be converted to a byte stream to be written to a file that byte stream can be converted back into a copy of the object when read from the file. The Serializable interface has no methods to implement. All we need to do is: import the java.io.Serializable interface add implements Serializable to the class header

276 The ObjectOutputStream Class
The ObjectOutputStream class, coupled with the FileOutputStream class, provide the functionality to write objects to a file. The ObjectOutputStream class provides a convenient way to write objects to a file. Its writeObject method takes one argument: the object to be written.

277 Constructors for Writing Objects
Class Constructor FileOutputStream FileOutputStream( String filename, boolean mode ) creates a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. ObjectOutputStream ObjectOutputStream( OutputStream out ) creates an ObjectOutputStream that writes to the OutputStream out. Throws an IOException.

278 The writeObject Method
See Examples FlightRecord2.java and Example WritingObjects.java Return value Method name and argument list void writeObject( Object o ) writes the object argument to a file. That object must be an instance of a class that implements the Serializable interface. Otherwise, a run-time exception will be generated. Throws an IOException.

279 Omitting Data from the File
The writeObject method does not write any object fields declared to be static or transient. You can declare a field as transient if you can easily reproduce its value or if its value is 0. Syntax to declare a field as transient: accessModifier transient dataType fieldName Example: private transient double totalRevenue;

280 SOFTWARE ENGINEERING TIP To save disk space when writing to an object file, declare the class's fields as static or transient, where appropriate.

281 Reading Objects from a File
The ObjectInputStream class, coupled with FileInputStream, provide the functionality to read objects from a file. The readObject method of the ObjectInputStream class is designed to read objects from a file. Because the readObject method returns a generic Object, we must type cast the returned object to the appropriate class. When the end of the file is reached, the readObject method throws an EOFException, so we detect the end of the file when we catch that exception.

282 Constructors for Reading Objects
Class Constructor FileInputStream FileInputStream( String filename ) constructs a FileInputStream object from a String representing the name of a file. Throws a FileNotFoundException. ObjectInputStream ObjectInputStream( InputStream in ) creates an ObjectInputStream from the InputStream in. Throws an IOException.

283 The readObject Method See Example 11.17 ReadingObjects.java
-- we detect reaching the end of the file in the catch block for EOFException we use a finally block to close the file. Return value Method name and argument list Object readObject( ) reads the next object and returns it. The object must be an instance of a class that implements the Serializable interface. When the end of the file is reached, an EOFException is thrown. Also throws an IOException and ClassNotFoundException

284 Graphical User Interfaces
Chapter 12 Graphical User Interfaces

285 Topics GUI Applications with JFrame GUI Components Labels
Event Handling Text Fields Command Buttons, Radio Buttons, and Checkboxes Combo Boxes Adapter Classes Mouse Movements Layout Managers

286 Introduction GUIs enable the user to
select the next function to be performed enter data set program preferences, such as colors or fonts display information GUIs also make the program easier to use a GUI is a familiar interface to users. Users can learn quickly to operate your program, in many cases, without consulting documentation or extensive training.

287 The JFrame Class The JFrame class, in the javax.swing package, allows you to display a window. JFrame is a Component, a graphical object that can be displayed Container, a component that holds other objects Window, a basic window Frame, a framed window

288 JFrame Constructors Constructor
constructs a JFrame object with no text in the title bar JFrame( String titleBarText ) constructs a JFrame object with titleBarText displayed in the window's title bar

289 Useful Methods of the JFrame Class
Applications extending JFrame inherit these methods. Return value Method name and argument list Container getContentPane( ) returns the content pane object for this window. We will add components to the content pane. void setDefaultCloseOperation( int operation ) sets the default operation when the user closes the window. setSize( int width, int height ) sizes the window to the specified width and height in pixels setVisible( boolean mode ) displays this window if mode is true; hides the window if mode is false

290 A Shell GUI Application
See Example 12.1 ShellGUIApplication.java Our application inherits from JFrame public class ShellGUIApplication extends JFrame The main method instantiates an instance of our application: ShellGUIApplication basicGui = new ShellGUIApplication( ); specifies that the application should terminate when the user closes the window: basicGui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

291 A Shell GUI Application (con't)
The GUI application constructor's job is to: call the constructor of the JFrame superclass get an object reference to the content pane container. We will add our GUI components to the content pane. set the layout manager. Layout managers arrange the GUI components in the window. instantiate each component add each component to the content pane set the size of the window make the window visible

292 Common Error Trap Be sure to call the setSize method to set the initial dimensions of the window and to call the setVisible method to display the window and its contents. Omitting the call to the setSize method will create a default JFrame consisting of a title bar only. If you omit the call to the setVisible method, the window will not open when the application begins.

293 GUI Components A component performs at least one of these functions:
displays information collects data from the user allows the user to initiate program functions. The Java Class Library provides a number of component classes in the javax.swing package

294 AWT Versus Swing Java supports two implementations of GUI components: AWT (Abstract Window Toolkit) and Swing. AWT components: the original implementation of Java components AWT hands off some of the display and behavior of the component to the native windowing system called heavyweight components Disadvantage: because of the inconsistencies in the look-and-feel of the various windowing systems, an application may behave slightly differently on one platform than on another.

295 AWT Versus Swing Swing Components Benefits:
second generation of GUI components developed entirely in Java to provide a consistent look and feel from platform to platform referred to as lightweight components Benefits: Applications run consistently across platforms The Swing architecture has its roots in the Model-View-Controller paradigm, which facilitates programming. An application can still take on the look-and-feel of the platform on which it is running, if desired.

296 Java Swing Components, part 1
Component/ Java Class Purpose Label / JLabel Displays an image or read-only text. Labels are often used to identify the contents of a text field. Text field / JTextField A single-line text box for displaying information and accepting user input Text area / JTextArea Multiple-line text field for data entry or display Password field / JPasswordField Single-line text field for accepting passwords without displaying the characters typed.

297 Java Swing Components, part 2
Component/ Java Class Purpose Button / JButton Command button used to signal that an operation should be performed Radio Button / JRadioButton Toggle button used to select one option in a group. Checkbox / JCheckBox Toggle button used to select 0, 1, or more options in a group. Drop-down List / JComboBox Drop-down list of items that the user clicks to select one item

298 Inheritance Hierarchy
for some GUI Classes

299 Useful JComponent Methods
Return value Method name and argument list void setVisible( boolean mode ) makes the component visible if mode is true; hides the component if mode is false. The default is visible. setToolTipText( String toolTip ) sets the tool tip text to toolTip. When the mouse lingers over the component, the toolTip text will be displayed. setForeground( Color foreColor ) sets the foreground color of the component to foreColor. setBackground( Color backColor ) sets the background color of the component to backColor.

300 More Useful JComponent Methods
Return value Method name and argument list void setOpaque( boolean mode ) sets the component's background to opaque if mode is true; sets the component's background to transparent if mode is false. If opaque, the background is filled with the component's background color; if transparent, the background is filled with the background color of the container on which it is placed. The default is transparent. setEnabled( boolean mode ) enables the component if mode is true, disables the component if mode is false. An enabled component can respond to user input.

301 Useful Container Methods
We use these methods to set up the organization of the components and to add and remove components from the window: Return value Method name and argument list void setLayout( LayoutManager mgr ) sets the layout manager of the window to mgr Component add( Component component ) adds the component to the window, using the rules of the layout manager. Returns the argument. removeAll( ) removes all components from the window

302 The FlowLayout Layout Manager
The FlowLayout layout manager arranges components in rows from left to right in the order in which the components are added to the container. Whenever a newly added component does not fit into the current row, the FlowLayout layout manager starts a new row. FlowLayout Constructor FlowLayout( ) creates a FlowLayout layout manager that centers components in the container.

303 The JLabel Component A JLabel label component does not interact with a user The JLabel displays some information, for example: a title an identifier for another component an image

304 JLabel Constructors Constructor
JLabel( String text ) creates a JLabel object that displays the specified text JLabel( String text, int alignment ) creates a JLabel object that displays the specified text. The alignment argument specifies the alignment of the text within the label component. The alignment value can be any of the following static int constants from the SwingConstants interface: LEFT, CENTER, RIGHT, LEADING, or TRAILING. By default, the label text is left-adjusted. JLabel( Icon image ) creates a JLabel object that displays the image.

305 Using JLabel Components
We instantiate two JLabels: labelText, which displays text We set the foreground and background colors and set the text to opaque. labelImage, which displays an image. We add some tooltip text See Example 12.2 Dinner.java

306 Common Error Trap As with any object reference, you must instantiate a component before using it. Forgetting to instantiate a component before adding it to the content pane will result in a NullPointerException at run time when the JVM attempts to display the component.

307 Common Error Trap Be sure to place the call to the setVisible method as the last statement in the constructor. If you add components to the window after calling setVisible, those components will not be displayed until the window contents are refreshed, or repainted.

308 Event Handling GUI programming uses an event-driven model of programming. The program responds to events caused by the user interacting with a GUI component. For example, we might display some text fields, a few buttons, and a selectable list of items. Then our program will "sit back" and wait for the user to do something. When the user enters text into a text field, presses a button, or selects an item from the list, our program will respond, performing the function that the user has requested, then sit back again and wait for the user to do something else.

309 Handling Events When the user interacts with a GUI component, the component fires an event. To allow a user to interact with our application through a GUI component, we need to perform the following functions:  1.   write an event handler class (called a listener) 2.   instantiate an object of that listener 3.   register the listener on one or more components Note that an application can instantiate more than one listener.

310 Listener Interfaces A typical event handler class implements a listener interface. The listener interfaces, which inherit from the EventListener interface, are supplied in the java.awt.event or javax.swing.event package. A listener interface specifies one or more abstract methods that an event handler class needs to override. The listener methods receive as a parameter an event object, which represents the event that was fired.

311 Event Class Hierarchy

312 Event Objects Event classes are subclasses of the EventObject class and are in the java.awt.event and javax.swing.event packages. From the EventObject class, event classes inherit the getSource method. Using simple if .. else if statements, your event handler can identify which component fired the event. Return value Method name and argument list Object getSource( ) returns the object reference of the component that fired the event

313 Events and Listeners JComponent User Activity Event Object
Listener Interface to Implement JTextField Pressing Enter ActionEvent ActionListener JButton Pressing the button JRadioButton Selecting a radio button ItemEvent ItemListener JCheckBox Selecting a checkbox

314 More Events and Listeners
JComponent User Activity Event Object Listener Interface to Implement JComboBox Selecting an item ItemEvent ItemListener Any component Pressing or releasing mouse buttons MouseEvent MouseListener Moving or dragging the mouse MouseMotion-Listener

315 Pattern for Event Handling
Constructor: public ClassName( ) // constructor { // call JFrame constructor // get content pane // set the layout manager // instantiate components // add components to the content pane // instantiate event handler objects // register event handlers on components // set window size // make window visible }

316 Registering a Listener
In the constructor, we instantiate an object of our event handler class. Then we register that event handler on one or more components by calling an add…Listener method. add…Listener APIs void addActionListener( ActionListener handler ) void addItemListener( ItemListener handler ) void addMouseListener( MouseListener handler ) void addMouseMotionListener( MouseMotionListener handler )

317 Common Error Trap If you do not register a listener on a component, the user will still be able to interact with the component (type into a text field, for example), but events generated by the user interaction will not be sent to the listener. Thus, even though you provide an event handler, if you do not register it on a component, the event handler will never execute.

318 Event Handler Pattern An event handler as a private inner class:
private class EventHandlerName implements ListenerName { // implement the listener interface methods // to process the events } A private inner class is defined within the public class and has access to all the members of the public class. When an event is fired on a registered component, the appropriate listener method executes automatically.

319 Text Fields We will write a GUI program that simulates a login, using these components: JTextField (a single line of text) for the User ID JPasswordField (a single line of text that echoes a special character for each character typed by the user) for the password JTextArea (multiple lines of text) See Example 12.3 to display a legal warning Login.java to potential hackers JLabels to label the text fields.

320 JTextField and JPasswordField Constructors
JTextField( String text ) creates a text field initially filled with text JTextField( int numberColumns ) constructs an empty text field with the specified number of columns JPasswordField JPasswordField( int numberColumns ) constructs an empty password field with the specified number of columns

321 JTextArea Constructors
JTextArea( String text ) constructs a text area initially filled with text JTextArea( int numRows, int numColumns ) constructs an empty text area with the number of rows and columns specified by numRows and numColumns JTextArea( String text, int numRows, int numColumns ) constructs a text area initially filled with text, and with the number of rows and columns specified by numRows and numColumns

322 Methods Common to JTextField, JTextArea, and JPasswordField
Return value Method name and argument list void setEditable( boolean mode ) sets the text component as editable or noneditable (read-only), depending on whether mode is true or false. The default is editable. setText( String newText ) sets the text of the text component to newText String getText( ) returns the text contained in the text component

323 Additional Methods of the JPasswordField Class
Return value Method name and argument list void setEchoChar( char c ) sets the echo character of the password field to c char[] getPassword( ) returns the text entered in this password field as an array of chars. Note: this method is preferred over the getText method for retrieving the password typed by the user.

324 The ActionListener Interface
An event handler that implements the ActionListener interface provides code in this method to respond to the ActionEvent fired by any registered components. public void actionPerformed( ActionEvent event )

325 Common Error Trap Be sure that the header of the listener method you override is coded correctly. Otherwise, your method will not override the abstract method, as required by the interface. For example, misspelling the actionPerformed method name as in this header: public void actionperformed( ActionEvent a ) will generate a compiler error: Login.TextFieldHandler is not abstract and does not override abstract method actionPerformed(ActionEvent)in ActionListener

326 Common Error Trap The java.awt.event package is not imported with the java.awt package. You will need both of these import statements: import java.awt.*; import java.awt.event.*;

327 JButton A JButton component implements a command button.
Clicking on a button generates an ActionEvent, so our listener should implement the ActionListener interface. JButton Constructor JButton( String buttonLabel ) creates a command button labeled with buttonLabel

328 JButton Example See Example 12.4 SimpleMath.java
The user enters a number into the text field and presses a button. The result is displayed as a JLabel. Our event handler uses the getSource method to determine which button was pressed.

329 JRadioButton and JCheckBox
Radio buttons are typically used to allow the user to select one option from a group. Radio buttons are meant to be mutually exclusive, in that clicking on any radio button deselects any previously selected radio button. Checkboxes often are associated with the sentence "check all that apply;" that is, the user may select 0, 1, or more options. A checkbox is a toggle button, in that successive clicks alternate between selecting and deselecting the option for that particular checkbox.

330 Creating a Group of JRadioButtons
To create a group of mutually exclusive radio buttons, we first instantiate the buttons: JRadioButton Constructors JRadioButton( String buttonLabel ) constructs a radio button labeled buttonLabel. By default, the radio button is initially deselected. JRadioButton( String buttonLabel, boolean selected ) constructs a radio button labeled buttonLabel. If selected is true, the button is initially selected; if selected is false, the button is initially deselected.

331 The ButtonGroup Class Then we instantiate a ButtonGroup and add the buttons to the group. A ButtonGroup object is used to define a mutually exclusive group of buttons. Constructor ButtonGroup( ) constructs a group for mutually exclusive radio buttons Return value Method name and argument list void add( AbstractButton button ) adds button to the button group. JRadioButton inherits from AbstractButton.

332 The ItemListener Interface
Clicking on a registered JRadioButton or a JCheckBox generates an ItemEvent, which is handled by an ItemListener. An event handler that implements the ItemListener interface provides code in this method to respond to the ItemEvent fired by any registered components. public void itemStateChanged( ItemEvent event )

333 Using Radio Buttons See Example 12.5 ChangingColors.java The red, green, and blue JRadioButtons are added to a ButtonGroup. The listener uses the getSource method to determine which radio button was selected and sets the background of a JLabel to the corresponding color.

334 JCheckBox Constructors
Because JCheckBoxes are designed to allow selection of multiple check boxes simultaneously, we do not use a button group. JCheckBox Constructors JCheckBox( String checkBoxLabel ) constructs a check box labeled checkBoxLabel. By default, the check box is initially deselected. JCheckBox( String checkBoxLabel, boolean selected ) constructs a checkbox labeled checkBoxLabel. If selected is true, the checkbox is initially selected; if selected is false, the checkbox is initially deselected.

335 A Useful ItemEvent Method
Each click (select and deselect) on a registered JCheckBox generates an ItemEvent. To distinguish between these states, we call the getStateChange method of the ItemEvent class. Return value Method name and argument list int getStateChange( ) If the checkbox is selected, the value SELECTED is returned; if the checkbox is deselected, the value DESELECTED is returned, where SELECTED and DESELECTED are static int constants of the ItemEvent class.

336 Using JCheckBoxes See Example 12.6 MixingColors.java
Using the getStateChange method, the listener sets the red, green, and blue color intensities depending on whether the checkbox is selected or deselected.

337 The JComboBox Component
The JComboBox implements a drop-down list. When the combo box appears, one item is displayed, along with a down-arrow button. When the user presses the button, the combo box "drops" open and displays a list of items, with a scroll bar for viewing more items. The user can select only one item from the list.   When the user selects an item, the list closes and the selected item is the one item displayed. A JComboBox fires an ItemEvent, so the event handler implements the ItemListener interface.

338 JComboBox Constructor/Methods
JComboBox<E>( E[] arrayName ) constructs a JComboBox initially filled with the objects of type E in arrayName. Often, the objects are Strings. Return value Method name and argument list int getSelectedIndex( ) returns the index of the selected item. The index of the first item in the list is 0. void setSelectedIndex( int index ) selects the item at index. The index of the first item in the list is 0. setMaximumRowCount( int size ) sets the number of items visible at one time.

339 Using a JComboBox See Example 12.8 FoodSamplings.java
The JComboBox items are an array of Strings. We also define a parallel array of ImageIcons with images corresponding to the country names. Initially, we programmatically select the third item using the setSelectedIndex method and initialize the food image label to display the third image.

340 SOFTWARE ENGINEERING TIP Arrange items in lists in a logical order so that the user can find the desired item quickly. For example, list items alphabetically or in numeric order. Also consider placing the most commonly chosen items at the top of the list.

341 Mouse Events For mouse events, there are two listeners:
the MouseListener interface specifies five methods to implement the MouseMotionListener interface specifies two methods to implement If we want to use a MouseListener, but need to use only one of its five methods to process a MouseEvent, we still have to implement the other four methods as "do-nothing" methods with empty method bodies.

342 Adapter Classes For convenience, Java provides adapter classes, each of which implements an interface and provides an empty body for each of the interface's methods. Thus, instead of implementing an interface, we can extend the appropriate adapter class and override only the method or methods we need. For mouse events, the adapter classes are MouseAdapter, which implements the MouseListener interface MouseMotionAdapter, which implements the MouseMotionListener interface

343 MouseEvents Any mouse activity (clicking, moving, or dragging) by the user generates a MouseEvent. To determine the (x, y) coordinate of the mouse event, we call these MouseEvent methods: Return value Method name and argument list int getX( ) returns the x value of the (x, y) coordinate of the mouse activity getY( ) returns the y value of the (x, y) coordinate of the mouse activity

344 MouseListener Interface Methods
public void mousePressed( MouseEvent e ) called when the mouse button is pressed public void mouseReleased( MouseEvent e ) called when the mouse is released after being pressed public void mouseClicked( MouseEvent e ) called when the mouse button is pressed and released public void mouseEntered( MouseEvent e ) called when the mouse enters a component public void mouseExited( MouseEvent e ) called when the mouse exits a component

345 Using the MouseAdapter Class
We implement a Submarine Hunt game. A submarine is hidden somewhere in the window, and the user will try to sink the submarine by clicking the mouse at various locations in the window, simulating the dropping of a depth charge. The only mouse action we care about is a click; therefore, we are interested in overriding only one method of the MouseListener interface: mouseClicked. To simplify our code, we extend the MouseAdapter class. The listener should handle mouse clicks anywhere in the window, so we register the MouseListener mh on the window (JFrame) component:   this.addMouseListener( mh );

346 The Model-View-Controller Architecture
The Model encapsulates the application's functionality The View encapsulates the user interface of the application The Controller is the middleman between the View and the Model. When the user interacts with the View, the Controller asks the Model to perform some calculations, and then updates the View accordingly. Separating the Model, View, and Controller functionality makes the application easier to design, code, maintain, and reuse.

347 The Sub Hunt Game We create three classes:
SubHunt, encapsulates the game functionality – creates the game, enables play, enforces the rules. SubHuntViewController, combines the View and Controller to provide the user interface. PlaySubHunt, which provides the client.

348 The Sub Hunt Game UML

349 JFrame Borders A JFrame window has borders called insets.
The x, y coordinates returned by the mouse event are relative to the top left corner of the window. We need to adjust the x and y coordinates so that the game is played inside a rectangle that excludes the insets.

350 The Insets Class Provides four public int variables containing the size in pixels of each border. top, left, bottom, right We access these values through an Insets object returned by the getInsets method inherited from the Container class. Return value Method name and argument list Insets getInsets( ) returns an object representing the insets of this Container

351 The translate Method In order to draw the result of the last click, in the paint method, we first call the translate method of the Graphics class, passing the left and top insets to adjust the click position of the coordinate to the top-left corner of the sub hunt rectangle. Return value Method name and argument list void translate( int x, int y ) translates the origin of the graphics context to the point (x, y) in the current coordinate system

352 Updating the Window Two cases require us to update the window:
When the submarine has been hit, we want to draw the "sunken" submarine . If the mouse click is more than two lengths from the center of the submarine, we want to draw a blue circle. However, we cannot call the paint method explicitly. Instead, we call the repaint method (inherited from the Component class): Return value Method name and argument list void repaint( ) automatically forces a call to the paint method

353 Removing a Listener In the mouse handler, if the mouse click has hit the submarine, we "unregister" the mouse listener using the following method inherited from the Component class. After doing so, further mouse clicks will no longer cause the handler to be called. Return value Method name and argument list void removeMouseListener( MouseListener mh ) removes the mouse listener mh so that it is no longer registered on this component.

354 A Treasure Hunt Game We implement a treasure hunt game:
we hide a treasure in the window. the user attempts to find the treasure by moving the mouse around the window. we indicate how close the mouse is to the treasure by displaying a message at the mouse location. when the user moves the mouse over the treasure, we draw the treasure and remove the listener to end the game.

355 Implementing the Game Again we write three classes:
TreasureHunt is the Model and encapsulates the game functionality. TreasureHuntViewController combines the View and Controller and implements the user interface. PlayTreasureHunt contains main which instantiates the other two classes. See Examples – 12.14

356 The Treasure Hunt UML

357 We Use the MouseMotionListener Interface
Instead of coding the event handler as a private inner class, we define our TreasureHuntViewController class as implementing the MouseMotionListener interface. As a result, our class is a listener, and we register the listener on itself: addMouseMotionListener( this ); public void mouseMoved( MouseEvent e ) called when the mouse is moved onto a component public void mouseDragged( MouseEvent e ) called when the mouse is pressed on a component and the mouse is dragged

358 Layout Managers Layout Managers determine how the components are organized in the window. Three Layout Managers are: FlowLayout Adds components left to right in rows GridLayout Adds components to a table-like grid with equally sized cells BorderLayout Adds a component to any of five predefined areas

359 GridLayout The GridLayout organizes the container as a grid.
We can visualize the layout as a table made up of equally sized cells in rows and columns. Each cell can contain one component The first component added to the container is placed in the first column of the first row; the second component is placed in the second column of the first row, and so on. When all the cells in a row are filled, the next component added is placed in the first cell of the next row.

360 GridLayout Constructors
GridLayout( int numberRows, int numberColumns ) creates a grid layout with the number of rows and columns specified by the arguments. GridLayout( int numberRows, int numberColumns, int hGap, int vGap ) creates a grid layout with the specified number of rows and columns and with a horizontal gap of hGap pixels between columns and a vertical gap of vGap pixels between rows. Horizontal gaps are also placed at the left and right edges, and vertical gaps are placed at the top and bottom edges.

361 Using GridLayout See Example 12.15 ChessBoard.java We implement the
chessboard as a two- dimensional array of JButtons. When a button is pressed, we compose the corresponding text from two arrays containing the letters and digits.

362 Dynamic Layouts Layout managers can be instantiated dynamically based on run-time parameters or user input. Layouts also can be changed at run time. We write a Tile Puzzle Game where we randomly generate the grid size before each new game.

363 The Tile Puzzle Game UML
See Examples

364 The Tile Puzzle Game We use a GridLayout populated with buttons.
To simplify the event processing of the 2-D array of buttons, we create a reusable GridButton class that extends JButton, and has two instance variables, row and column. Our event processor code then becomes: public void actionPerformed( ActionEvent ae ) { GridButton button = ( GridButton ) ae.getSource( ); if ( game.tryToPlay( button.getRow( ), button.getColumn( ) ) ) update( ); }

365 Dynamically Changing the Layout
To change the grid size for each new game we randomly generate a new puzzle size 2. remove all the components contents.removeAll( ); 3. set the layout to a new GridLayout with the rows and columns set to the puzzle size.

366 BorderLayout A BorderLayout organizes a container into five areas:

367 BorderLayout Areas Each area can hold at most one component.
The size of each area expands or contracts depending on: the size of the component in that area the sizes of the components in the other areas whether the other areas contain a component.

368 Using a BorderLayout BorderLayout is the default layout manager for a JFrame object. so if we want to use a border layout for our GUI applications, we do not need to instantiate a new layout manager. BorderLayout Constructors BorderLayout( ) creates a border layout with no gaps between components BorderLayout( int hGap, int vGap ) creates a border layout with a horizontal gap of hGap pixels between components and a vertical gap of vGap pixels between components.

369 Adding Components to a BorderLayout
To add components to a container with a BorderLayout layout manager, we use this method inherited from the Container class. Return value Method name and argument list void add( Component c, Object borderlayoutArea ) adds the component c to the container. The area defined by borderlayoutArea can be specified using any of the following static String constants from the BorderLayout class: NORTH, SOUTH, EAST, WEST, CENTER

370 Using a BorderLayout A Color Mixer Application
We place a JButton in each of the NORTH, EAST, WEST, and SOUTH areas, and a JLabel in the CENTER area.

371 The Color Mixer UML See Examples 12.20 – 12.23
We now separate the View and Controller. The Controller has references to the Model and to the View.

372 Nesting Components Components can be nested.
Because the JComponent class is a subclass of the Container class, a JComponent object is a Container object as well. As such, it can contain other components. We can use this feature to nest components to achieve more precise layouts.

373 Using JPanels to Nest Components
The JPanel class is a general-purpose container, or a panel, and is typically used to hold other components. We usually place several components into a JPanel, then add the JPanel to the content pane as a single component. Each JPanel has its own layout manager, and the content pane for the JFrame application has its own layout manager. We can even have multiple levels of nesting.

374 Guess the Most Frequent Color Game
The GUI The Underlying Layout

375 A Reusable Controller Instead of using a class for the Model, the Controller uses an interface. public class Controller { private ModelInterface model; The ModelInterface specifies methods that the Controller will call to manage the game. The Model class uses this pattern: public class Model implements ModelInterface // ModelInterface methods here }

376 Color Frequency UML See Examples – 12.28


Download ppt "Introduction to Object-Oriented Programming: Using Classes"

Similar presentations


Ads by Google