1、類與對(duì)象概念
- 類:類是對(duì)具有某一共同特性的事物的的集合,是一種抽象化的概念。
- 對(duì)象:對(duì)象是對(duì)類這一概念的具體實(shí)現(xiàn),是真實(shí)世界的實(shí)體。比如,我們將人看做類的話,那么“我”、“小明”、“小龍”等就是一個(gè)個(gè)具體的對(duì)象。
2. 對(duì)象與引用
public class Person {
public static void main(String[] args) {
Person p = new Person();
}
}
對(duì)于Person p = new Person();,很多人都會(huì)認(rèn)為p是對(duì)象,這種理解其實(shí)是錯(cuò)誤的。p是引用變量,它存儲(chǔ)在棧中,new Person()會(huì)創(chuàng)建一個(gè)新的person對(duì)象存儲(chǔ)在堆中,然后將存儲(chǔ)地址傳遞給引用變量p。
2、this關(guān)鍵字
- this關(guān)鍵字表示“這個(gè)對(duì)象”或“當(dāng)前對(duì)象”,而且它本身表示對(duì)當(dāng)前對(duì)象的引用。
- this關(guān)鍵字只能在方法(不包括靜態(tài)方法)內(nèi)部使用。
public class Banana {
private String name;
private String color;
public Banana() {}
public Banana(String name) {
this.name = name; // this.name表示這個(gè)對(duì)象的屬性name
}
public Banana(String name, String color) {
this(name); // 調(diào)用構(gòu)造器
this.color = color;
}
public static void f1() {
// this.name; // error
}
}
3、 static關(guān)鍵字
- static方法的內(nèi)部不能調(diào)用非靜態(tài)方法
- 無(wú)論創(chuàng)建多少對(duì)象,靜態(tài)數(shù)據(jù)都只占用一份存儲(chǔ)區(qū)域,static關(guān)鍵字不能作用在于局部變量,因?yàn)樗荒茏饔糜谟颉?/li>
public class Test {
public static void main(String[] args) {
System.out.println("水果1...");
Fruit fruit1 = new Fruit();
System.out.println("水果2...");
Fruit fruit2 = new Fruit();
}
}
class Apple {
Apple() {
System.out.println("蘋(píng)果真好吃");
}
}
class Fruit {
static Apple apple = new Apple();
static {
System.out.println("靜態(tài)代碼塊...");
}
Fruit() {
System.out.println("Fruit init...");
}
public void f() {
// static int i = 1; // error
}
}
水果1...
蘋(píng)果真好吃
靜態(tài)代碼塊...
Fruit init...
水果2...
Fruit init...
由結(jié)果可知,靜態(tài)初始化會(huì)先執(zhí)行,而且只在第一次加載Fruit.class的時(shí)候執(zhí)行,然后再調(diào)用構(gòu)造器生成對(duì)象。
dui
訪問(wèn)權(quán)限
| 權(quán)限 | 類內(nèi) | 同包 | 不同包子類 | 不同包非子類 |
|---|---|---|---|---|
| private | √ |
× | × | × |
| default | √ |
√ |
× | × |
| protected | √ |
√ |
√ |
× |
| public | √ |
√ |
√ |
√ |