Chapter 9 Objects and Classes Liang Introduction to

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

Objectives q q q q 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 define classes and create objects (§ 9. 3). To create objects using constructors (§ 9. 4). To access objects via object reference variables (§ 9. 5). To access 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 (§ 9. 5. 3). 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 develop methods with object arguments (§ 9. 10). To store and process objects in arrays (§ 9. 11). To create immutable objects 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. 2

OO Programming Concepts l Object-oriented programming (OOP) involves programming using objects. l An object represents an entity in the real world that can be distinctly identified (清楚地識別). l For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. l An object has a unique identity, state, and behaviors. l The state of an object consists of a set of data fields (also known as properties) with their current values. l The behavior of an object is defined by a set of methods. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 3

Simple Examples of Objects l An object has both a state and behavior. l 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. 4

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

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

UML Class Diagram 結構有 三個部分 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 7

Example: Defining Classes and Creating Objects Objective : l Demonstrate l creating objects, l accessing data, and l using methods. Listing 9. 1 (p. 348) Test. Simple. Circle. java Test. Simple. Circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Run 8

Example: Defining Classes and Creating Objects Listing 9. 3, 9. 4 (p. 351~352) TV. java, Test. TV. java TV Test. TV Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Run 9

Constructors l Constructors are a special kind of methods that are invoked to construct objects, e. g. , Circle UML Circle() { } Circle(double new. Radius) { radius = new. Radius; } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 10

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

Creating Objects Using Constructors Syntax (語法) : l new Class. Name(); Example : l new Circle(); l new Circle(5. 0); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 12

Default Constructor A class may be defined without constructors. l In this case, a no-arg constructor with an empty body is implicitly (內隱) defined in the class. l 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. 13

Declaring Object Reference Variables l l To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: Class. Name object. Ref. Var; l Example: Circle my. Circle; 有點像變數的宣稱,如下 : int x; Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 14

Declaring and Creating Objects in a Single Step Syntax (語法) : l Class. Name object. Ref. Var = new Class. Name(); 同一類別名稱 Example : l Assign object reference Create an object Circle my. Circle = new Circle(); 同一類別名稱 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 15

Accessing (取用) Object’s Members q Referencing (參照、取用) the object’s data: l Syntax : object. Ref. Var. data l Example : my. Circle. radius q Invoking l l (呼叫) the object’s method: Syntax : object. Ref. Var. method. Name(args) Example : my. Circle. get. Area() Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 16

animation Trace Code Declare my. Circle = new Circle(5. 0); my. Circle no value Circle your. Circle = new Circle(); your. Circle. radius = 100; Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 17

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle no value Circle your. Circle = new Circle(); your. Circle. radius = 100; Create a circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 18

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle your. Circle = new Circle(); your. Circle. radius = 100; reference value Assign object reference to my. Circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 19

animation Trace Code, cont. my. Circle reference value your. Circle no value Circle my. Circle = new Circle(5. 0); Circle your. Circle = new Circle(); your. Circle. radius = 100; Declare your. Circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 20

animation Trace Code, cont. my. Circle reference value your. Circle no value Circle my. Circle = new Circle(5. 0); Circle your. Circle = new Circle(); your. Circle. radius = 100; Create a new Circle object Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 21

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle reference value Circle your. Circle = new Circle(); your. Circle. radius = 100; your. Circle reference value Assign object reference to your. Circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 22

animation Trace Code, cont. my. Circle reference value Circle my. Circle = new Circle(5. 0); Circle your. Circle = new Circle(); your. Circle. radius = 100; your. Circle reference value Change radius in your. Circle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 23

Caution Recall that we use Math. method. Name(arguments) (e. g. , Math. pow(3, 2. 5) ) to invoke a method in the Math class. l Can we invoke get. Area() using Simple. Circle. get. Area() ? l The answer is no. l All the methods used before this chapter are static methods, which are defined using the static keyword. l However, get. Area() is non-static. It must be invoked from an object using l object. Ref. Var. method. Name(arguments) (e. g. , my. Circle. get. Area() ). l my. Circle More explanations will be given in the section on “Static Variables, Constants, and Methods. ” Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 24

Reference Data Fields l l The data fields of a class 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 is. IM_Major; // is. IM_Major has default value false char gender; // c has default value 'u 0000' } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 25

The null Value l 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. 26

Default Value for a Data Field l l The default (預設) value for a data field of an object is l null for a reference type, l 0 for a numeric type, l false for a boolean type, and l 'u 0000' 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("is. IM_Major? " + student. is. IM_Major); System. out. println("gender? " + student. gender); } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 27

Example l 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. 28

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

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

The Date Class l l Java provides date and time in the java. util. Date class. We can use the Date class to create an instance for the current date and time and use its to. String 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. 31

The Date Class Example For example, the following code java. util. Date date = new java. util. Date(); System. out. println(date. to. String()); displays a string like Sun Mar 26 14: 50: 19 EST 2020. Eastern Standard Time (東部標準時間) Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 32

The Random Class l l We use 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. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 33

The Random Class Example l l 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 random 1 = new Random(3); System. out. print("From random 1: "); for (int i = 0; i < 10; i++) System. out. print(random 1. next. Int(1000) + " "); Random random 2 = new Random(3); System. out. print("n. From random 2: "); for (int i = 0; i < 10; i++) System. out. print(random 2. next. Int(1000) + " "); From random 1: 734 660 210 581 128 202 549 564 459 961 From random 2: 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. 34

The Point 2 D Class l Java API (Application Programming Interface) has a conveninent Point 2 D class in the javafx. geometry package for representing a point in a two-dimensional plane. Listing 9. 5 (p. 360) Test. Point 2 D. java Test. Point 2 D Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Run 35

Instance Variables, and Methods l Instance variables (個例變數,即是物件變數) belong to a specific instance. l Instance methods (個例方法,即是物件方法) are invoked by an instance of the class. Instance (個例,個別例子) ~ object 物件(object)是類別(class)的個別例子 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 36

Static Variables, Constants, and Methods l Static variables (靜態變數,即是類別變數) are shared by all the instances (objects) of the class. l Static methods (靜態方法,即是類別方法) are not tied to a specific instance (object). l Static constants (靜態常數,即是類別常數) are final variables shared by all the instances of the class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 37

Static Variables, Constants, and Methods, cont. l To declare static variables, constants, and methods, use the static modifier. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 38

Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. l This example adds a class variable (static variable) number. Of. Objects to track the number of Circle objects created. l Listing 9. 6, 9. 7 (p. 362~363) scenario Circle. With. Static. Members Test. Circle. With. Static. Member s Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Run 39

Static Variables, Constants, and Methods, cont. 個別物件的變數 static variable 所有同類物件的共 有變數(類別變數) static method 個別物件的變數 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 40

Visibility Modifiers (可見性修飾詞) and Accessor/Mutator Methods l By default, the class, variable, or method can be accessed by any class in the same package. l public The class, variable, or method is visible to any class in any package. l private The variable or method can be accessed only by the declaring class. l The get and set methods are used to read and modify private properties (variables or methods). Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 41

l The private (私有的) modifier restricts access to within a class, l The default (預設的) modifier restricts access to within a package l The public (公開的) modifier enables unrestricted access. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 42

l The default modifier on a class restricts access to within a package, and l the public modifier enables unrestricted access. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 43

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

Why Data Fields Should Be private? l To protect data. l To make code easy to maintain. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 45

Example of Data Field Encapsulation (封裝) underline: static variable or method Listing 9. 8, 9. 9 (p. 369~370) Circle. With. Private. Data. Fields Test. Circle. With. Private. Data. Fields Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Run 46

Passing Objects to Methods q Passing by value for primitive type value (the value is passed to the parameter) q Passing by value for object reference value (the value is the reference (address pointer) pointing to the object) scenario for passing values Listing 9. 10 (p. 372) Test. Pass. Object. java Test. Pass. Object Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 47

Passing Objects to Methods, cont. Call print. Area() 對Circle物件所作 的更動,在離開print. Area() 回到main()之後, 可看到 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All Circle物件所被作的更動 rights reserved. 48
![Array of Objects Circle[] circle. Array = new Circle[10]; for (int i = 0; Array of Objects Circle[] circle. Array = new Circle[10]; for (int i = 0;](http://slidetodoc.com/presentation_image_h2/69ac06441d7849f1ad84ceba208840f7/image-49.jpg)
Array of Objects Circle[] circle. Array = new Circle[10]; for (int i = 0; i < circle. Array. length; i++) { circle. Array[i] = new Circle(Math. random() * 100); } l l An array of objects is actually an array of reference (pointer) variables. circle. Array references to the entire array. circle. Array[1] references to a Circle object. So invoking circle. Array[1]. get. Area() involves two levels of referencing as shown in the next figure. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 49
![Array of Objects, cont. Circle[] circle. Array = new Circle[10]; for (int i = Array of Objects, cont. Circle[] circle. Array = new Circle[10]; for (int i =](http://slidetodoc.com/presentation_image_h2/69ac06441d7849f1ad84ceba208840f7/image-50.jpg)
Array of Objects, cont. Circle[] circle. Array = new Circle[10]; for (int i = 0; i < circle. Array. length; i++) { circle. Array[i] = new Circle(Math. random() * 100); } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 50

Array of Objects, cont. Summarizing the areas of the circles Listing 9. 11 (p. 376) Total. Area. java Total. Area Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 51

Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable (不變的) object and its class is called an immutable class. l If we delete the set method in the Circle class in Listing 8. 10, the class would be immutable because radius is private and cannot be changed without a set method. l A class with all private data fields and without mutators is not necessarily immutable. l For example, the following class Student has all private data fields and no mutators, but it is mutable. Because it contains a mutable private data field : a Birth. Date object. l Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 52

Example public class Student { private int id; private Birth. Date birth. Date; public class Birth. Date { private int year; private int month; private int day; public Student(int ssn, int year, int month, int day) { id = ssn; birth. Date = new Birth. Date(year, month, day); } public Birth. Date(int new. Year, int new. Month, int new. Day) { year = new. Year; month = new. Month; day = new. Day; } public int get. Id() { return id; } public Birth. Date get. Birth. Date() { return birth. Date; } } public void set. Year(int new. Year) { year = new. Year; } } public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); Birth. Date date = student. get. Birth. Date(); date. set. Year(2010); // Now the student birth year is changed! } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 53

What Class is Immutable? l For a class to be immutable, it must l mark all data fields private, and l provide no mutator methods, and l provide no accessor methods that would return a reference to a mutable data field object. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 54

Scope of Variables q The scope (範圍) of instance and static variables is the entire class. q They can be declared anywhere inside a class. q The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. q 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. 55

The this Keyword q The this keyword is the name of a reference that refers to an object itself. q One common use of the this keyword is reference a class’s hidden data fields. q 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. 56

Reference the Hidden Data Fields Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 57

Calling Overloaded Constructor 當不會產生混淆時,可不用this Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 58
- Slides: 58