Lecture 10 Introduction to Classes and Objects Java
Lecture 10: Introduction to Classes and Objects Java How to Program, Late Objects Version, 8/e © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 1 Introduction In this chapter, we present a simple framework for organizing object-oriented applications in Java. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 2 Classes, Objects, Methods and Instance Variables Simple analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. ◦ Before you can drive a car, someone has to design it ◦ A car typically begins as engineering drawings, similar to the blueprints used to design a house. ◦ These include the design for an accelerator pedal to make the car go faster. ◦ The pedal “hides” from the driver the complex mechanisms that actually make the car go faster, just as the brake pedal “hides” the mechanisms that slow the car and the steering wheel “hides” the mechanisms that turn the car. ◦ Enables people with little or no knowledge of how engines work to drive a car easily. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 2 Classes, Objects, Methods and Instance Variables (cont. ) Cannot drive a car’s engineering drawings ◦ Before you can drive a car, it must be built from the engineering drawings that describe it ◦ A completed car has an actual accelerator pedal to make the car go faster, but even that’s not enough—the car won’t accelerate on its own, so the driver must press the accelerator pedal © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 2 Classes, Objects, Methods and Instance Variables (cont. ) Performing a task in a program requires a method. ◦ The method declaration describes the mechanisms that actually perform its tasks. ◦ The method hides from its user the complex tasks that it performs. ◦ In Java, we begin by creating a program unit called a class to house a method, just as a car’s engineering drawings house the design of an accelerator pedal. ◦ You provide one or more methods that are designed to perform the class’s tasks. Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object of a class before you can get a program to perform the tasks the class describes how to do © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 2 Classes, Objects, Methods and Instance Variables (cont. ) When you drive a car, pressing its gas pedal sends a message to the car to perform a task—that is, make the car go faster. Similarly, you send messages to an object—each message is a method call that tells a method of the object to perform its task. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 2 Classes, Objects, Methods and Instance Variables (cont. ) A car, in addition to it’s capabilities, also has many attributes, such as its color, the number of doors, the amount of gas in its tank, its current speed and its total miles driven. ◦ These attributes are represented as part of a car’s design in its engineering diagrams ◦ As you drive a car, these attributes are always associated with the car ◦ Every car maintains its own attributes © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 2 Classes, Objects, Methods and Instance Variables (cont. ) Similarly, an object has attributes that are carried with the object as it’s used in a program ◦ These attributes are specified as part of the object’s class ◦ Attributes are specified by the class’s instance variables © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class In this section, you create a new class, then use it to create an object. We begin with an example that consists of classes Grade. Book (Fig. 7. 1) and Grade. Book. Test (Fig. 7. 2). Class Grade. Book (declared in file Grade. Book. java) will be used to display a message on the screen (Fig. 7. 2) welcoming the instructor to the grade book application. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont’d) Class Grade. Book. Test (declared in file Grade. Book. Test. java) is an application class in which the main method will create and use an object of class Grade. Book. ◦ Such an application class is sometimes called a test harness. Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the. java file-name extension. ◦ Thus, classes Grade. Book and Grade. Book. Test will be declared in separate files. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) A class normally consists of one or more methods that manipulate the attributes that belong to a particular object of the class. Attributes are represented as variables in a class declaration © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Such variables are called fields and are declared inside a class declaration but outside the bodies of the class’s method declarations. When each object of a class maintains its own copy of an attribute, the field that represents the attribute is also known as an instance variable. ◦ Each object (instance) of the class has a separate instance of the variable in memory © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Class Grade. Book (Fig. 7. 1) maintains the course name as an instance variable so that it can be used or modified at any time during an application’s execution © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The class contains three methods: 1. set. Course. Name: stores a course name in a Grade. Book 2. get. Course. Name: obtains a Grade. Book’s course name 3. display. Message: displays a welcome message that includes the course name; as you’ll see, the method obtains the course name by calling another method in the same class —get. Course. Name © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The keyword public is an access modifier. Every class declaration contains keyword class followed immediately by the class’s name. Every class’s body is enclosed in a pair of left and right braces. ◦ For now, we’ll simply declare every class public © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) A variable that is declared in the body of the class but outside the bodies of the class’s methods is an instance variable. ◦ Every instance of the class contains one copy of each instance variable. All the methods of the class can manipulate any instance variables that appear in the class. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Most instance-variable declarations are preceded with the keyword private. Like public, keyword private is an access modifier. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Variables or methods declared with access modifier private are accessible only to methods of the class in which they’re declared. Declaring instance variables with access modifier private is known as data hiding or information hiding © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The methods you declared in earlier chapters were all static methods. In this class, the methods are not declared with keyword static. A non-static method can call any method of the same class directly and can manipulate any of the class’s fields directly. A static method can call only other static methods of the same class directly and can manipulate only static fields in the same class directly. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Class Grade. Book cannot execute the application because it does not contain main. To fix this problem, we must either declare a separate class that contains a main method or place a main method in class Grade. Book. To help you prepare for the larger programs you’ll encounter later in this book and in industry, we use a separate class containing method main to test each new class we create in this chapter. ◦ Some programmers refer to such a class as a driver class © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Class Grade. Book. Test (Fig. 7. 2) creates one object of class Grade. Book and demonstrates its methods. Typically, you cannot call a method that belongs to another class until you create an object of that class. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Each new class you create becomes a new type that can be used to declare variables and create objects. You can declare new class types as needed; this is one reason why Java is known as an extensible language. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) A class instance creation expression uses keyword new to create a new object of the class specified to the right of the keyword. ◦ The parentheses to the right of the class name are required. ◦ The parentheses in combination with a class name represent a call to a constructor, which is similar to a method but is used only at the time an object is created to initialize the object’s data. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Unlike local variables, which are not automatically initialized, every field has a default initial value. ◦ Provided by Java when you do not specify the field’s initial value. Reference-type instance variables are initialized by default to the value null—a reserved word that represents a “reference to nothing. ” © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Primitive-type instance variables of types byte, char, short, int, long, float and double are initialized to 0, and variables of type boolean are initialized to false You can specify your own initial value for a variable by assigning the variable a value in its declaration © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Scanner method next. Line reads characters typed by the user until the newline character is encountered, then returns a String containing the characters up to, but not including, the newline. ◦ The newline character is discarded Class Scanner also provides a similar method— next—that reads individual words. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) A class’s private fields can be manipulated only by the class’s methods. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Classes often provide public methods to allow clients to set (i. e. , assign values to) or get (i. e. , obtain the values of) private instance variables. ◦ The names of these methods need not begin with set or get, but this naming convention is recommended. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) You must compile the classes in Fig. 7. 1 and Fig. 7. 2 before you can execute the application. The following command compiles both classes: javac Grade. Book. java Grade. Book. Test. java © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) If the directory containing the application includes only this application’s files, you can compile all the classes in the directory with the command javac *. java ◦ The asterisk (*) in *. java indicates that all files in the current directory that end with the file-name extension “. java” should be compiled. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) Figure 7. 3 presents a UML class diagram for class Grade. Book in Fig. 7. 1 In the UML, each class is modeled in a class diagram as a rectangle with three compartments. ◦ The top one contains the name of the class centered horizontally in boldface type ◦ The middle compartment contains the class’s attributes, which correspond to instance variables in Java ◦ The bottom compartment contains the class’s operations, which correspond to methods in Java © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The UML represents instance variables as attributes by listing the attribute name, followed by a colon and the attribute type. Instance variable course. Name is private in Java, so the class diagram lists a minus sign (–) access modifier in front of the corresponding attribute’s name. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The UML models operations by listing the operation name preceded by an access modifier (in this case + to represent public) and followed by a set of parentheses. The UML indicates the return type of an operation by placing a colon and the return type after the parentheses following the operation name. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The import declaration in Fig. 7. 2 indicates to the compiler that the program uses class Scanner. Why do we need to import class Scanner, but not classes System, String or Grade. Book? ◦ Classes System and String are in package java. lang, which is implicitly imported into every Java program, so all programs can use that package’s classes without explicitly importing them ◦ Most other classes you’ll use in Java programs must be imported explicitly © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) There is a special relationship between classes that are compiled in the same directory on disk. ◦ Such classes are considered to be in the same package—known as the default package. ◦ Classes in the same package are implicitly imported into the source-code files of other classes in the same package. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 3 Declaring a Class and Instantiating an Object of that Class (cont. ) The import declaration in line 3 is not required if we always refer to class Scanner as java. util. Scanner, which includes the full package name and class name. ◦ This is known as the class’s fully qualified class name. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 4 Initializing Objects with Constructors Each class you declare can provide a special method called a constructor that can be used to initialize an object of a class when the object is created. Java requires a constructor call for every object that is created. Keyword new requests memory from the system to store an object, then calls the corresponding class’s constructor to initialize the object. ◦ The call is indicated by the parentheses after the class name. A constructor must have the same name as the class. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 4 Initializing Objects with Constructors (cont. ) For example, line 14 of Fig. 7. 2 first uses new to create a Grade. Book object. The empty parentheses after “new Grade. Book” indicate a call to the class’s constructor without arguments. The compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor. ◦ When a class has only the default constructor, its instance variables are initialized to their default values. When you declare a class, you can provide your own constructor to specify custom initialization for objects of your class Figure 7. 4 contains a modified Grade. Book class with a constructor that receives an argument. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 4 Initializing Objects with Constructors (cont. ) Like a method, a constructor’s parameter list specifies the data it requires to perform its task. ◦ When you create a new object, this data is placed in the parentheses that follow the class name. A class instance creation expression returns a reference to the new object. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 4 Initializing Objects with Constructors (cont. ) An important difference between constructors and methods is that constructors cannot return values, so they cannot specify a return type (not even void). Normally, constructors are declared public. If you declare any constructors for a class, the Java compiler will not create a default constructor for that class. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 4 Initializing Objects with Constructors (cont. ) The UML class diagram of Fig. 7. 6 models class Grade. Book of Fig. 7. 4, which has a constructor that has a name parameter of type String. Like operations, the UML models constructors in the third compartment of a class in a class diagram. To distinguish a constructor from a class’s operations, the UML requires that the word “constructor” be placed between guillemets ( « and » ) before the constructor’s name. It’s customary to list constructors before other operations in the third compartment. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 4 Initializing Objects with Constructors (cont. ) Sometimes you’ll want to initialize objects with multiple pieces of data. Like methods, constructors can specify any number of parameters. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 5 Case Study: Account Balances; Validating Constructor Arguments Our next application (Figs. 7. 7– 7. 8) contains a class named Account (Fig. 7. 7) that maintains the balance of a bank account. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 6 Case Study: Account Balances; Validating Constructor Arguments The class has a constructor and two methods. It’s common for someone opening an account to deposit money immediately, so the constructor receives a parameter initial. Balance of type double that represents the starting balance. ◦ Lines 14– 15 validate the constructor argument to ensure that initial. Balance is greater than 0. 0. ◦ If so, initial. Balance’s value is assigned to instance variable balance. ◦ Otherwise, balance remains at 0. 0—its default initial value. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 6 Case Study: Account Balances; Validating Constructor Arguments (cont. ) Class Account. Test (Fig. 7. 8) creates and manipulates two Account objects. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 6 Case Study: Account Balances; Validating Constructor Arguments (cont. ) The UML class diagram in Fig. 7. 9 models class Account of Fig. 7. 7. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 7 Case Study: Card Shuffling and Dealing Simulation In our next example, we manipulate an array of objects. Elements of an array can be either primitive types or reference types. This section uses random-number generation and an array of Card objects, to develop a class that simulates card shuffling and dealing. We first develop class Card (Fig. 7. 10), which represents a playing card that has a face and a suit. Next, we develop the Deck. Of. Cards class (Fig. 7. 11), which creates a deck of 52 playing cards in which each element is a Card object. We then build a test application (Fig. 7. 12) that demonstrates class Deck. Of. Cards’s card shuffling and dealing capabilities. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 7 Case Study: Card Shuffling and Dealing Simulation (cont. ) Class Card (Fig. 7. 10) contains two String instance variables— face and suit—that are used to store references to the face name and suit name for a specific Card. Method to. String creates a String consisting of the face of the card, the String " of " and the suit of the card All objects have a to. String method that returns a String representation of the object When an object is concatenated with a String or used where a String is expected (e. g. , when printf outputs the object as a String using the %s format specifier), the object’s to. String method is implicitly called to obtain the String representation of the object. ◦ For this behavior to occur, to. String must be declared with the header shown in Fig. 7. 10. © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 7 Case Study: Card Shuffling and Dealing Simulation (cont. ) Class Deck. Of. Cards (Fig. 7. 11) declares as an instance variable a Card array named deck (line 7). Class Deck. Of. Cards also declares an integer instance variable current. Card representing the next Card to be dealt from the deck array and a named constant NUMBER_OF_CARDS indicating the number of Cards in the deck (52). The class’s constructor instantiates the deck array. When first created, the elements of the deck array are null by default, so the constructor uses a for statement to fill the deck array with Cards When the deck array is initialized, it contains the Cards with faces "Ace" through "King" in order for each suit ("Hearts" then "Diamonds" then "Clubs" then "Spades") © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 7 Case Study: Card Shuffling and Dealing Simulation (cont. ) Method shuffles the Cards in the deck. For each Card, a number between 0 and 51 is picked randomly to select another Card. Next, the current Card object and the randomly selected Card object are swapped in the array. After the for loop terminates, the Card objects are randomly ordered Method deal. Card deals one Card in the array. If the deck is not empty, line 53 returns the “top” Card and postincrements current. Card to prepare for the next call to deal. Card—otherwise, null is returned. ◦ Recall that null represents a “reference to nothing. ” © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
7. 7 Case Study: Card Shuffling and Dealing Simulation (cont. ) Figure 7. 12 demonstrates class Deck. Of. Cards (Fig. 7. 11) © 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2010 by Pearson Education, Inc. All Rights Reserved.
- Slides: 78