0% found this document useful (0 votes)
7 views51 pages

CH 07

Uploaded by

hafsasohail577
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views51 pages

CH 07

Uploaded by

hafsasohail577
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Chapter 7

Introduction to Classes and Objects


Java How to Program, 11/e, Global Edition
(Late Objects Version)
Questions? E-mail [email protected]

Copyright © 2018 Pearson Education, Ltd. All Rights Reserved


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2 Instance Variables, set Methods and get Methods
 Each class you create becomes a new type that can be used to declare variables
and create objects.
 You can declare new classes as needed; this is one reason Java is known as an
extensible language.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2.1 Account Class with an Instance Variable, a set Method and a get
Method (Cont.)
Class Declaration
 Each class declaration that begins with the access modifier public must be stored in a file
that has the same name as the class and ends with the .java filename extension.
 Every class declaration contains keyword class followed immediately by the class’s name.
Identifiers and Camel Case Naming
 Class, method and variable names are identifiers.
 By convention all use camel case names.
 Class names begin with an uppercase letter, and method and variable names begin with a
lowercase letter.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.1 Account Class with an Instance Variable, a set Method and a get
Method (Cont.)

Instance Variable name


 An object has attributes that are implemented as instance variables and carried with it throughout its
lifetime.
 Instance variables exist before methods are called on an object, while the methods are executing and
after the methods complete execution.
 A class normally contains one or more methods that manipulate the instance variables that belong to
particular objects of the class.
 Instance variables are declared inside a class declaration but outside the bodies of the class’s method
declarations.
 Each object (instance) of the class has its own copy of each of the class’s instance variables.

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2.1 Account Class with an Instance Variable, a set Method and a get
Method (Cont.)

Access Modifiers public and private


 Most instance-variable declarations are preceded with the keyword private, which is an
access modifier.
 Variables or methods declared with access modifier private are accessible only to methods
of the class in which they’re declared.

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.


7.2.1 Account Class with an Instance Variable, a set Method and a get
Method (Cont.)

Instance method setName of class Account


 In the preceding chapters, you’ve declared only static methods in each class.
 A class’s non-static methods are known as instance methods.
 Method setName’s declaration indicates that setName receives parameter name of type
String—which represents the name that will be passed to the method as an argument.
 Recall that variables declared in the body of a particular method are local variables and can be
used only in that method and that a method’s parameters also are local variables of the method.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.1 Account Class with an Instance Variable, a set Method and a get
Method (Cont.)
 Method setName’s body contains a single statement that assigns the value of the name
parameter (a String) to the class’s name instance variable, thus storing the account name in
the object.
 If a method contains a local variable with the same name as an instance variable, that method’s
body will refer to the local variable rather than the instance variable.
 In this case, the local variable is said to shadow the instance variable in the method’s body.
 The method’s body can use the keyword this to refer to the shadowed instance variable
explicitly.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2.1 Account Class with an Instance Variable, a set Method and a get
Method (Cont.)

getName method of class Account


 Method getName returns a particular Account object’s name to the caller.
 The method has an empty parameter list, so it does not require additional information to
perform its task.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.2 AccountTest Class That Creates and Uses an
Object of Class Account
Driver class AccountTest
 A class that creates an object of another class, then calls the object’s methods, is a driver class.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2.2 AccountTest Class That Creates and Uses an Object of
Class Account (Cont.)

Scanner object for receiving input from the user


 Scanner method nextLine reads characters until a newline character is encountered, then
returns the characters as a String.
 Scanner method next reads characters until any white-space character is encountered, then
returns the characters as a String.
◦ Useful to read a single word

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.2 AccountTest Class That Creates and Uses an Object of Class
Account (Cont.)

Instantiating an Object—Keyword new and Constructors


 A class instance creation expression begins with keyword new and creates a new object.
 A constructor is similar to a method but is called implicitly by the new operator to initialize an
object’s instance variables at the time the object is created.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.2 AccountTest Class That Creates and Uses an Object of
Class Account (Cont.)

Calling class Account’s getName method


 To call a method of an object, follow the object name with a dot separator, the method name
and a set of parentheses containing the method’s arguments.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2.2 AccountTest Class That Creates and Uses an Object of Class
Account (Cont.)

null—the default initial value for String variables


 Local variables are not automatically initialized.
 Every instance variable has a default initial value—a value provided by Java when you do not
specify the instance variable’s initial value.
 The default value for an instance variable of type String is null.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.2 AccountTest Class That Creates and Uses an Object of
Class Account (Cont.)

Calling class Account’s setName method


 A method call supplies values—known as arguments—for each of the method’s parameters.
 Each argument’s value is assigned to the corresponding parameter in the method header.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.3 Compiling and Executing an App with Multiple
Classes
 The javac command can compile multiple classes at once.
 Simply list the source-code filenames after the command with each filename separated by a
space from the next.
 If the directory containing the app includes only one app’s files, you can compile all of its
classes with the command javac *.java.
 The asterisk (*) in *.java indicates that all files in the current directory ending with the
filename extension “.java” should be compiled.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.4 Account UML Class Diagram with an Instance Variable and set
and get Methods
 We’ll often use UML class diagrams to summarize a class’s attributes and operations.
 UML diagrams help systems designers specify a system in a concise, graphical, programming-
language-independent manner, before programmers implement the system in a specific
programming language.
 Figure 7.3 presents a UML class diagram for class Account of Fig. 7.1.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.4 Account UML Class Diagram with an Instance Variable and set
and get Methods (Cont.)

Top Compartment
 In the UML, each class is modeled in a class diagram as a rectangle with three compartments.
 The top one contains the class’s name centered horizontally in boldface.
Middle Compartment
 The middle compartment contains the class’s attributes, which correspond to instance
variables in Java.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.4 Account UML Class Diagram with an Instance Variable and set
and get Methods (Cont.)

Bottom Compartment
 The bottom compartment contains the class’s operations, which correspond to methods and
constructors in Java.
 The UML represents instance variables as an attribute name, followed by a colon and the type.
 Private attributes are preceded by a minus sign (–) in the UML.
 The UML models operations by listing the operation name followed by a set of parentheses.
 A plus sign (+) in front of the operation name indicates that the operation is a public one in the
UML (i.e., a public method in Java).

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.4 Account UML Class Diagram with an Instance Variable and set
and get Methods (Cont.)

Return Types
 The UML indicates an operation’s return type by placing a colon and the return type after the
parentheses following the operation name.
 UML class diagrams do not specify return types for operations that do not return values.
 Declaring instance variables private is known as data hiding or information hiding.
Parameters
 The UML models a parameter of an operation by listing the parameter name, followed by a
colon and the parameter type between the parentheses after the operation name

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.5 Additional Notes on This Example
Notes on static methods
 A static method can call other static methods of the same class directly (i.e., using the method
name by itself) and can manipulate static variables in the same class directly.
 To access the class’s instance variables and instance methods, a static method must use a reference
to an object of the class.
 Instance methods can access all fields (static variables and instance variables) and methods of the
class.
 Many objects of a class, each with its own copies of the instance variables, may exist at the same time.
 Java does not allow a static method to directly access instance variables and instance methods of the
same class.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.2.5 Additional Notes on Class AccountTest (Cont.)

Notes on import declarations


 Most classes you’ll use in Java programs must be imported explicitly.
 There’s a special relationship between classes that are compiled in the same directory.
 By default, 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 that

package.
 An import declaration is not required when one class in a package uses another in the same package.
 An import- declaration is not required if you always refer to a class with its fully qualified class name,

which includes its package name and class name.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.2.6 Software Engineering with private Instance Variables and public
set and get Methods
 Declaring instance variables private is known as data hiding or information hiding.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.3 Default and Explicit Initialization for Instance Variables
 Recall that local variables are not initialized by default.
 Primitive-type instance variables are initialized by default—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 primitive-type instance variable explicitly by
assigning the variable a value in its declaration, as in
private int numberOfStudents = 10;
 Reference-type instance variables (such as those of type String), if not explicitly initialized,
are initialized by default to the value null—which represents a “reference to nothing.”

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.4 Account Class: Initializing Objects with Constructors
 Each class you declare can optionally provide a constructor with parameters 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’s created.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.4.1 Declaring an Account Constructor for Custom Object
Initialization
 Figure 7.5 contains a modified Account class with such a constructor.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.4.2 Class AccountTest: Initializing Account Objects When
They’re Created
 The AccountTest program (Fig. 7.6) initializes two Account objects using the constructor.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.4.2 Class AccountTest: Initializing Account Objects When They’re
Created (Cont.)

Constructors cannot return values


 Constructors can specify parameters but not return types.

Default Constructor
 If a class does not define constructors, the compiler provides a default constructor with no
parameters, and the class’s instance variables are initialized to their default values.

There’s no default Constructor in a class that declares a Constructor


 If you declare a constructor for a class, the compiler will not create a default constructor for that
class.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.4.2 Class AccountTest: Initializing Account Objects When They’re
Created (Cont.)

Adding the Contructor to class Account’s UML Class Diagram


 The UML models constructors in the third compartment of a class diagram.
 To distinguish a constructor from a class’s operations, the UML places the word “constructor”
between guillemets (« and ») before the constructor’s name.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.5 Account Class with a Balance; Floating-Point Numbers

 We now declare an Account class that maintains the balance of a bank account in addition
to the name.
 Most account balances are not integers.
 So, class Account represents the account balance as a double.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


7.5.1 Account Class with a balance Instance Variable of
Type double
 Our next app contains a version of class Account (Fig. 7.8) that maintains as instance
variables the name and the balance of a bank account.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.5.2 AccountTest Class to Use Class Account
 Class AccountTest (Fig. 7.9) creates two Account objects and initializes them with a valid
balance of 50.00 and an invalid balance of -7.53, respectively—for the purpose of our
examples, we assume that balances must be greater than or equal to zero.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
7.5.2 AccountTest Class to Use Class Account (Cont.)
 The default value for an instance variable of type double is 0.0, and the default value for an
instance variable of type int is 0.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.
Classes and Objects
 Video Lectures : Object Oriented Programming Using Java by Sir Asif
Shahzad, Assistant Professor, Computer Science Department, CUI
Lahore
◦ Lec05 - OOP/Java - Concept of Class and Object (youtube.com)
◦ Lec06 - OOP/Java - Adding Behavior in Object (youtube.com)
◦ Lec07 - Java/OOP - Data Hiding and Encapsulation (youtube.com)

©1992-2018 by Pearson Education, Inc. All Rights Reserved.


<< Home Tasks >>

 Prepare the Self Review Exercise Questions (7.1-7.3).


 Complete the Programming Exercises: 7.10, 7.11, 7.12, 7.14, 7.22, 7.23
 Suggested Programming Exercise(s) for Assignment Grading: 7.23

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

You might also like