ch8 OBJECTS AND CLASSES

8-1 Introduction

p.288 Figure 8.2 The GUI objects are created from classes.

8-2 Defining Classes for Objects

An object represents an entity in the real world that can be distinctly identified The state of an object (also known as its properties or attributes) is represented by data fields with their current values. The behavior of an object (also known as its actions) is defined by methods.
An object is an instance of a class.

p.288 Figure 8.2 A class is a template(contract, blueprint) for creating objects

p.289 Figure 8.3 A class is a construct that defines objects of the same type

It does not have a main method and therefore cannot be run

p.2 Figure 8.4 Classes and objects can be represented using UML notations

UML Class Diagram

UML 前面符號

──────────────────────────────────
Class name
─────────────☼─────────────────────
Data fields
──────────────────────────────────
Constructors and methods
──────────────────────────────────
constructor 建構子
ClassName(parameterName: parameterType)
method 方法
methodName(parameterName: parameterType): returnType

8-3 Example: Defining Classes and Creating Objects

課堂解說 Class

參考 p.290 程式 Listing 8.1 TestCircle1.java

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
一個檔案,可以有1個以上的class,但只能有1個加上public修飾詞,且此java檔案名字要和此public class一致,若執行時,從此public class的 main 開始執行

參考 p.291 程式 Listing 8.2 Circle1.java

宣告與產生物件
Circle1 myCircle = new Circle1(5.0);
一般而言,class檔案會分散在不同的檔案內,這時候需要考慮 package的觀念(以後解說)與修飾詞
Java宣告類別、成員變數,成員方法,可以加上修飾詞

p.292 Figure 8.5 The TV class models TV sets

參考 p.292 程式 Listing 8.3 TV.java

TV class 因為沒有 main ,不能直接執行

參考 p.293 程式 Listing 8.4 TestTV.java

8-4 Constructing Objects Using Constructors

Constructors A class normally provides a constructor without arguments such a constructor is referred to as a no-arg or no-argument constructor A class may be defined without constructors 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

8-5 Accessing Objects via Reference Variables

8-5-1 Reference Variables and Reference Types

// 宣告物件變數
ClassName objectRefVar;

Circle myCircle;

// 產生真正的物件,並用 myCircle 指到(reference) 到物件所在(in heap)
myCircle = new Circle();

// 宣告與產生物件,合併為1個步驟
ClassName objectRefVar = new ClassName();

Circle myCircle = new Circle();

p.295 Note. An object reference variable and object ( 重要觀念 參考 Figure 8.6, Figure 8.8)

p.295 Note. Arrays are treated as objects in Java, created using the new operator

8-5-2 Accessing an Object’s Data and Methods

invoked using the dot operator (.) 使用英文句點
// 範例
objectRefVar.dataField
myCircle.radius

objectRefVar.method(arguments)
myCircle.getArea()

p.296 Caution. 可以使用 Math.pow(3, 2.5) static vs. 不可以使用 Circle.getArea() NOT static

p.296 Note. create an object without explicitly assigning it to a variable new Circle()

8-5-3 Reference Data Fields and the null Value

The data fields can be of reference types. class 內的每個 Data Field 都會給予初值
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'
}

null is a literal for a reference type, null表示變數沒有指到任何物件

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); 
	}
}
Method 內的區域變數(Local Variable),並不會自動給予初值(initial value)
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); 
	}
}

p.297 Caution. NullPointerException

8-5-4 Differences Between Variables of Primitive Types and Reference Types (重要)

Primitive type int i = 1 
Object type Circle c = new Circle()

重要 p.297 Figure 8.6 variable of a primitive type vs variable of a reference type holds a reference

Primitive type assignment i = j

重要 p.297 Figure 8.7 Primitive variable j is copied to variable i.

Object type assignment c1 = c2

重要 p.298 Figure 8.8 Reference variable c2 is copied to variable c1.

p.298 Note. The object previously referenced by c1 is no longer useful and therefore is now known as garbage, garbage collection

p.298 Tip. assign null to a reference variable for the object, 表示物件不會用到了,Java VM 執行 garbage collection 時,會將該物件所佔用的記憶體回收,提供以後 需要配置記憶體時 使用

8-6 Using Classes from the Java Library

8-6-1 The Date Class

p.298 Figure 8.9 A Date object represents a specific date and time.

8-6-2 The Random Class

Math.random() vs java.util.Random (功能較多)

p.299 Figure 8.10 A Random object can be used to generate random values.

// 產生 [0 .. n) 之間的整數
nextInt(n: int)

8-6-3 Displaying GUI Components

注意檔案開始的 import javax.swing.JFrame; (快速鍵 Ctrl + Shift + O 自動更新 import)

參考 p.300 程式 Listing 8.5 TestFrame.java

參考 p.300 程式 Listing 8.6 GUIComponents.java

除了Swing的GUI展示外,若有時間,展示 Android

8-7 Static Variables, Constants, and Methods

The data field radius in the circle class is known as an instance variable. If all the instances of a class to share data, use static variables, also known as class variables. Static methods can be called without creating an instance of the class.

重要 p.302 Figure 8.12 Instance variables and Static variables

static int numberOfObjects;
static int getNumberObjects() {
	return numberOfObjects;
}

final static double PI = 3.14159265358979323846;

參考 p.303 程式 Listing 8.7 Circle2.java

參考 p.303 程式 Listing 8.8 TestCircle2.java

class Circle2 {
	double radius;
	static int numberOfObjects = 0; // The number of the objects created

p.304 Tip. use class name to invoke a static method and access a static variable

ClassName.staticMethodName(arguments)
ClassName.staticVariable

Static method 只能呼叫 static method, access static variable

public class Foo {
	int i = 5;
	static int k = 2;
	public static void main(String[] args) {
		int j = i;// Wrong because i is an instance variable
		m1(); // Wrong because m1() is an instance method 
	}
	public void m1() {
		// Correct since instance and static variables and methods 
		// can be used in an instance method
		i = i + k + m2(i, k); 
	 }
	public static int m2(int i, int j) {
		return (int)(Math.pow(i, j)); 
	}
}

如何access instance variable, method?

產生Class的物件,再使用物件去 access non-static variables, methods

public class Foo {
	int i = 5;
	static int k = 2;
	public static void main(String[] args) {
		Foo foo = new Foo();
		int j = foo.i;// 
		foo.m1(); // 
	}
	public void m1() {
		// Correct since instance and static variables and methods 
		// can be used in an instance method
		i = i + k + m2(i, k); 
	 }
	public static int m2(int i, int j) {
		return (int)(Math.pow(i, j)); 
	}
}

8-8 Visibility Modifiers

p.306 Note. package packageName;

Visibility Modifiers
package packageName; // packageName 通常為網址倒過來 例如 tw.edu.scu.csim.hello

重要 p.306 Figure 8.13 default and private, public modifier

package p1;
	public class C1 {
	public int x;
	int y;
	private int z;
	public void m1() { }
	void m2() {}
	private void m3() {}
}
package p1;
public class C2 {
	void aMethod()  {
		C1 o = new C1();
		can access o.x; 
		can access o.y; 
		cannot access o.z; 
		can invoke o.m1();
		can invoke o.m2();
		cannot invoke o.m3();
	}
}
package p2;
	public class C3 {
		void aMethod()  {
			C1 o = new C1();
			can access o.x; 
			cannot access o.y; 
			cannot access o.z; 
			can invoke o.m1();
			cannot invoke o.m2();
			cannot invoke o.m3();
	}
}

重要 p.306 Figure 8.14 nonpublic class has package-access

package p1;
class C1 {
	...
}
package p1;
public class C2 {
	can access C1
}
package p2;
public class C3 {
	cannot access C1;
	can access C2; 
}

重要 p.307 Figure 8.15 private members

p.307 Caution. public and private on local variables ERROR

p.307 Note. private constructor

What happen if public member ? using the private modifier. This is known as data field encapsulation

8-9 Data Field Encapsulation

p.208 Note. getter(or accessor) and setter (or mutator).

getter
public returnType getPropertyName()
If the returnType is boolean, getter
public boolean isPropertyName()
setter
public void setPropertyName(dataType propertyValue)

p.308 Figure 8.16 The Circle class encapsulates circle properties and provides get/set and other methods

參考 p.308 程式 Listing 8.9 Circle3.java

參考 p.309 程式 Listing 8.10 TestCircle3.java

8-10 Passing Objects to Methods

參考 p.310 程式 Listing 8.11 TestPassObject.java

p.311 Figure 8.17 n is passed to times, and the reference of myCircle is passed to c in the printAreas method.

passing methods

8-11 Array of Objects

Declares and creates an array of ten Circle objects:
Circle[] circleArray = new Circle[10];
To initialize the circleArray, you can use a for loop like this one:
for (int i = 0; i < circleArray.length; i++) {
	circleArray[i] = new Circle();
}
An array of objects is actually an array of reference variables.

重要 p.312 Figure 8.18 In an array of objects, an element of the array contains a reference to an object

p.312 Note. 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.

參考 p.312 程式 Listing 8.12 TotalArea.java