Java @Ch8. OBJECTS AND CLASSES 2010.12.10. Outline Reference Variables and Reference Types Primitive...
-
date post
21-Dec-2015 -
Category
Documents
-
view
230 -
download
2
Transcript of Java @Ch8. OBJECTS AND CLASSES 2010.12.10. Outline Reference Variables and Reference Types Primitive...
Outline
• Reference Variables and Reference Types• Primitive Types and Reference Types• Static Variable, Constants, and Methods• Visibility Modifiers• Displaying GUI Components
[Sample code]
Reference Variables and Reference Types
• Objects are accessed via object reference variables.
宣告範例 :
Car car1;
• A class is a reference type, which means that a variable of the class type can reference an instance of the class.
• Create an object and assigns its reference to car1.
car1 = new Car();
Combine: Car car1 = new Car(); ( 課本p.295)
補充 : ( 課本 p.296)
Usually you create an object and assign it to a variable. Later you can use the variable to reference the object.
new Car();
or
System.out.println
( “ 耗油量 : ” + Car().OilConsume(10) );
有時候你也可以不用宣告object reference variable 而直接呼叫 class 的方法
Primitive Types and Reference Types
• Primitive type:
int i = 1; i
• Object type:
Car car1; car1
1
reference Cac
carName = BMW
car1: Car
Create using new Car()
memory
( 課本 p.297)
• Primitive type:
i = j
• Object type:
car1 = car2
1
2
2
2j j
i i
Cac
carName = BMW
car2: Car Cac
carName = TOYOTA
car1: Car Cac
carName = BMW
car2: Car Cac
carName = TOYOTA
car1: Car
1
1
1
1car2 car2
car1 car1
X
Static Variable, Constants, and Methods
Static( 靜態 ):
靜態的含意是 , 程式建立之初 , 系統就已經先配置好一塊 Memory space 給它了 .
Static Variable
Static variables store values for the variables in a common memory location.
Car car1 = new Car();
Car car2 = new Car();
speed
position
speed
position
carID
drive()stop()
printID()
drive()stop()
printID()
static variable
car1 car2
data field
method
class 就可以直接做呼叫 , 不需要實作出 instance 來呼叫
Static Method
Static method can be called without creating an instance of the class. (p.302)
EX: Car.printID();
static methodclass name
class 就可以直接做呼叫 , 不需要實作出 instance 來呼叫
Static Constant
Constants in a class are shared by all objects of the class.
必須宣告成 final static
EX: final static double PI = 3.14159265;
class 就可以直接做呼叫 , 不需要實作出 instance 來呼叫
Visibility Modifiers
Package: can be used to organize classes.
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(); }}
• If a class is not defined public, it can be accessed only within the same package.
package p1;class C1{
}
package p1;public class C2{ can access C1;}
package p2;public class C3{ cannot access C1; can access C2;}