Java基礎(chǔ):對(duì)象

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容