Chapter 9 Objects and Classes Liang, Introduction to Java

92 Slides3.64 MB

Chapter 9 Objects and Classes Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 1

Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. In this chapter, we will start discussing object-oriented programming concepts. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 2

Objectives To describe objects and classes, and use classes to model objects (§9.2). To use UML graphical notation to describe classes and objects (§9.2). To demonstrate how to define classes and create objects (§9.3). To create objects using constructors (§9.4). To access objects via object reference variables (§9.5). To define a reference variable using a reference type (§9.5.1). To access an object’s data and methods using the object member access operator (.) (§9.5.2). To define data fields of reference types and assign default values for an object’s data fields (§9.5.3). To distinguish between object reference variables and primitive data type variables (§9.5.4). To use the Java library classes Date, Random, and Point2D (§9.6). To distinguish between instance and static variables and methods (§9.7). To define private data fields with appropriate get and set methods (§9.8). To encapsulate data fields to make classes easy to maintain (§9.9). To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments (§9.10). To store and process objects in arrays (§9.11). To create immutable objects from immutable classes to protect the contents of objects (§9.12). To determine the scope of variables in the context of a class (§9.13). To use the keyword this to refer to the calling object itself (§9.14). Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 3

OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 4

OO Programming Concepts The state of an object (also known as its properties or attributes) is represented by data fields with their current values. A circle object, for example, has a data field radius, which is the property that characterizes a circle. A rectangle object has the data fields width and height, which are the properties that characterize a rectangle The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object is to ask the object to perform an action. For example, you may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke getArea() to return its area and getPerimeter() to return its perimeter. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 5

OO Programming Concepts Objects of the same type are defined using a common class. A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be. An object is an instance of a class. You can create many instances of a class. Creating an instance is referred to as instantiation. The terms object and instance are often interchangeable. The relationship between classes and objects is analogous to that between an apple-pie recipe and apple pies: You can make as many apple pies as you want from a single recipe. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 6

Objects Class Name: Circle A class template Data Fields: radius is Methods: getArea Circle Object 1 Circle Object 2 Circle Object 3 Data Fields: radius is 10 Data Fields: radius is 25 Data Fields: radius is 125 Three objects of the Circle class An object has both a state and behavior. The state defines the object, and the behavior defines what the object does. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 7

Classes Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 8

Classes class Circle { /** The radius of this circle */ double radius 1.0; /** Construct a circle object */ Circle() { } Data field Constructors /** Construct a circle object */ Circle(double newRadius) { radius newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; } Method } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 9

Classes The Circle class is different from all of the other classes you have seen thus far. It does not have a main method and therefore cannot be run; it is merely a definition for circle objects. The class that contains the main method will be referred to in this book, for convenience, as the main class. The illustration of class templates and objects in can be standardized using Unified Modeling Language (UML) notation. This notation is called a UML class diagram, or simply a class diagram. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 10

Unified Modeling Language (UML) Class Diagram In the class diagram, the data field is denoted as dataFieldName: dataFieldType The constructor is denoted as: ClassName(parameterName: parameterType) The method is denoted as methodName(parameterName: parameterType): returnType Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 11

Example: SimpleCircle class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 12

Example: SimpleCircle class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 13

Example: SimpleCircle class The program contains two classes. The first of these, TestSimpleCircle, is the main class. Its sole purpose is to test the second class, SimpleCircle. Such a program that uses the class is often referred to as a client of the class. When you run the program, the Java runtime system invokes the main method in the main class. You can put the two classes into one file, but only one class in the file can be a public class. Furthermore, the public class must have the same name as the file name. Therefore, the file name is TestSimpleCircle.java, since TestSimpleCircle is public. Each class in the source code is compiled into Liang, file. IntroductionWhen to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. a .class you compile 14 All rights reserved.

Combine Two Classes into One Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 15

Combine Two Classes into One Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 16

Example: Defining Classes and Creating Objects TV The sign indicates a public modifier. channel: int volumeLevel: int The current channel (1 to 120) of this TV. on: boolean Indicates whether this TV is on/off. TV() turnOn(): void Constructs a default TV object. turnOff(): void setChannel(newChannel: int): void Turns off this TV. setVolume(newVolumeLevel: int): void channelUp(): void Sets a new volume level for this TV. channelDown(): void volumeUp(): void Decreases the channel number by 1. volumeDown(): void Decreases the volume level by 1. The current volume level (1 to 7) of this TV. Turns on this TV. Sets a new channel for this TV. Increases the channel number by 1. Increases the volume level by 1. The constructor and methods in the TV class are defined public so they can be accessed from other classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 17

Example: Defining Classes and Creating Objects Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 18

Example: Defining Classes and Creating Objects Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 19

Constructors Circle() { } Constructors are a special kind of methods that are invoked to construct objects. Circle(double newRadius) { radius newRadius; } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 20

Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 21

Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 22

Default Constructor A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 23

Declaring Object Reference Variables Objects are accessed via the object’s reference variables, which contain references to the objects. To reference an object, assign the object to a reference variable. A class is a reference type, which means that a variable of the class type can reference an instance of the class. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle; Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 24

Declaring/Creating Objects in a Single Step ClassName objectRefVar new ClassName(); Example: Assign object reference Create an object Circle myCircle new Circle(); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 25

Accessing Object’s Members Referencing the object’s data is done using the dot operator or object member access operator: objectRefVar.data e.g., myCircle.radius Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea() Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 26

Trace Code Declare myCircle Circle myCircle new Circle(5.0); myCircle no value Circle yourCircle new Circle(); yourCircle.radius 100; Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 27

Trace Code, cont. Circle myCircle new Circle(5.0); myCircle no value Circle yourCircle new Circle(); : Circle yourCircle.radius 100; radius: 5.0 Create a circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 28

Trace Code, cont. Circle myCircle new Circle(5.0); myCircle reference value Circle yourCircle new Circle(); yourCircle.radius 100; Assign object reference to myCircle : Circle radius: 5.0 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 29

Trace Code, cont. Circle myCircle new Circle(5.0); myCircle reference value Circle yourCircle new Circle(); yourCircle.radius 100; : Circle radius: 5.0 yourCircle no value Declare yourCircle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 30

Trace Code, cont. Circle myCircle new Circle(5.0); reference value myCircle Circle yourCircle new Circle(); : Circle yourCircle.radius 100; radius: 5.0 no value yourCircle : Circle Create a new Circle object radius: 1.0 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 31

Trace Code, cont. Circle myCircle new Circle(5.0); myCircle reference value Circle yourCircle new Circle(); : Circle yourCircle.radius 100; radius: 5.0 yourCircle reference value Assign object reference to yourCircle : Circle radius: 1.0 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 32

Trace Code, cont. Circle myCircle new Circle(5.0); reference value myCircle Circle yourCircle new Circle(); : Circle yourCircle.radius 100; radius: 5.0 yourCircle reference value : Circle Change radius in yourCircle radius: 100.0 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 33

Caution The data field radius is referred to as an instance variable, because it is dependent on a specific instance. For the same reason, the method getArea is referred to as an instance method, because you can invoke it only on a specific instance. The object on which an instance method is invoked is called a calling object. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 34

Caution Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using SimpleCircle.getArea()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is nonstatic. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()). Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 35

Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 36

The null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 37

Default Value for a Data Field The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { Student student new Student(); System.out.println("name? " student.name); System.out.println("age? " student.age); System.out.println("isScienceMajor? " student.isScienceMajor); System.out.println("gender? " student.gender); } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 38

Example Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " x); System.out.println("y is " y); } } Compile error: variable not initialized Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 39

Differences between Variables of Primitive Data Types and Object Types Every variable represents a memory location that holds a value. When you declare a variable, you are telling the compiler what type of value the variable can hold. For a variable of a primitive type, the value is of the primitive type. For a variable of a reference type, the value is a reference to where an object is located. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 40

Copying Variables of Primitive Data Types and Object Types Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 41

Garbage Collection As shown in the previous figure, after the assignment statement c1 c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 42

Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 43

The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 44

The Date Class Example Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 45

The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class. java.util.Random Random() Constructs a Random object with the current time as its seed. Random(seed: long) Constructs a Random object with a specified seed. nextInt(): int Returns a random int value. nextInt(n: int): int Returns a random int value between 0 and n (exclusive). nextLong(): long Returns a random long value. nextDouble(): double Returns a random double value between 0.0 and 1.0 (exclusive). nextFloat(): float Returns a random float value between 0.0F and 1.0F (exclusive). nextBoolean(): boolean Returns a random boolean value. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 46

The Random Class Example If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. Random random1 new Random(3); System.out.print("From random1: "); for (int i 0; i 10; i ) System.out.print(random1.nextInt(1000) " "); Random random2 new Random(3); System.out.print("\nFrom random2: "); for (int i 0; i 10; i ) System.out.print(random2.nextInt(1000) " "); From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 47

The Point2D Class Java API has a conveninent Point2D class in the javafx.geometry package for representing a point in a twodimensional plane. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 48

The Point2D Class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 49

Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by any instance of the class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 50

Static Variables, Constants, and Methods Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Because of this, a static method cannot access instance members of the class Static constants are final variables shared by all the instances of the class. A non-static (or instance) variable is tied to a specific instance Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 51

Static Variables, Constants, and Methods Static variables store values for the variables in a common memory location. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected. Java supports static methods as well as static variables. Static methods can be called without creating an instance of the class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 52

Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier. For example, the constant PI in the Math class is defined as final static double PI 3.14159265358979323846 Let’s modify the Circle class by adding a static variable numberOfObjects to count the number of circle objects created. When the first object of this class is created, numberOfObjects is 1. When the second object is created, numberOfObjects becomes 2. The UML of the new circle class is shown below Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 53

Static Variables, Constants, and Methods, cont. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 54

CircleWithStaticMembers Class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 55

TestCircleWithStaticMembers.java Static variables and methods can be accessed without creating objects. Line 6 displays the number of objects, which is 0, since no objects have been created. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 56

Static and Instance Methods An instance method can invoke an instance or static method and access an instance or static data field. A static method can invoke a static method and access a static data field. However, a static method cannot invoke an instance method or access an instance data field, since static methods and static data fields don’t belong to a particular object. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 57

Examples Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 58

Examples Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 59

Visibility Modifiers and Accessor/Mutator Methods You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access. Packages can be used to organize classes. To do so, you need to add the following line as the first statement in the program: package packageName; If a class is defined without the package statement, it is said to be placed in the default package. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 60

Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class. Public getter (Accessor) and setter (Mutator) methods are used to read and modify private properties. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 61

Examples The private modifier restricts access to within a class, The default modifier restricts access to within a package, The public modifier enables unrestricted access. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 62

Visibility Modifier of Classes The default modifier on a class restricts access to within a package The public modifier enables unrestricted access. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 63

NOTE An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a). Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 64

NOTE The private modifier applies only to the members of a class. The public modifier can apply to a class or members of a class. Using the modifiers public and private on local variables would cause a compile error. In most cases, the constructor should be public. However, if you want to prohibit the user from creating an instance of a class, use a private constructor. For example, there is no reason to create an instance from the Math class, because all of its data fields and methods are static. To prevent the user from creating objects from the Math class, the constructor in java.lang.Math is defined as private. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 65

Data Field Encapsulation Making data fields private protect data. Making data fields private helps to make code easy to maintain since the client programs cannot modify them. To prevent direct modifications of data fields, declaring the data fields private is known as data field encapsulation. To make a private data field accessible, provide a getter method to return its value. To enable a private data field to be updated, provide a setter method to set a new value. A getter method is also referred to as an accessor and a setter to a mutator. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 66

Example of Data Field Encapsulation Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 67

Example of Data Field Encapsulation Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 68

Example of Data Field Encapsulation Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 69

Example of Data Field Encapsulation Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 70

Passing Objects to Methods Passing by value for primitive type value (the value is passed to the parameter) Passing by value for reference type value (the value is the reference to the object) Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 71

Passing Objects to Methods Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 72

Passing a primitive type value and a reference value Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 73

Passing a primitive type value and a reference value When passing an argument of a reference type, the reference of the object is passed. In this case, c contains a reference for the object that is also referenced via myCircle. Therefore, changing the properties of the object through c inside the printAreas method has the same effect as doing so outside the method through the variable myCircle. Pass-by-value on references can be best described semantically as Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. pass-by-sharing; that is, Allthe object referenced in the74 rights reserved.

Passing Objects to Methods Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 75

Array of Objects Circle[] circleArray new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 76

Array of Objects Circle[] circleArray new Circle[10]; Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 77

Array of Objects To initialize circleArray, you can use a for loop for (int i 0; i circleArray.length; i ) { circleArray[i] new Circle(); } An array of objects is actually an array of reference variables. When an array of objects is created using the new operator, each element in the array is a reference variable with a default value of null. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 78

Summarizing the areas of the circles Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 79

Summarizing the areas of the circles Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 80

Summarizing the areas of the circles Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 81

Immutable Objects Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as immutable object and its class as immutable class. If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 82

Example Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 83

Example Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 84

Scope of Variables The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. The scope of a local variable (i.e. a variable defined in a method) starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 85

Scope of Variables Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 86

Scope of Variables If a local variable has the same name as a class’s variable, the local variable takes precedence and the class’s variable with the same name is hidden. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 87

The this Keyword The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields. Another common use of the this keyword to enable a constructor to invoke another constructor of the same class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 88

The this Keyword Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 89

Reference the Hidden Data Fields The this keyword can be used to reference a class’s hidden data fields. For example, a data-field name is often used as the parameter name in a setter method for the data field. In this case, the data field is hidden in the setter method. You need to reference the hidden data-field name in the method in order to set a new value to it. A hidden static variable can be accessed using the keyword this. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 90

Reference the Hidden Data Fields The this keyword gives us a way to reference the object that invokes an instance method. To invoke f1.setI(10), this.i i is executed, which assigns the value of parameter i to the data field i of this calling object f1. The keyword this refers to the object that invokes the instance method setI, as shown below: Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 91

Calling Overloaded Constructor The this keyword can be used to invoke another constructor of the same class. For example, you can rewrite the Circle class as follows: Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 92

Back to top button