最近在看JAVA教學的視頻,覺得老師講的很好,同時借用源代碼還有筆記來撰寫本系列博客,記錄自己的學習內容,同時也供看到的人學習。
繼續第十篇,這篇內容較少,主要是因爲與後面的聯繫不大,所以單成一篇。
這篇主要講static與this兩個JAVA保留字用法。
首先來說一說static,直譯爲靜止的,在JAVA作爲一種修飾的關鍵字用來修飾變量或者方法,使其成爲靜態變量或者靜態方法。
瞭解完static的大致內容後我們來看一看static在內存分配圖裏面的存在情況:
對應代碼:
public class Student {
//成員變量從屬於對象
String name;
int id;
//靜態變量從屬於類(內存中放在方法區)
static int ss;
public static void printSS(){
System.out.println(ss); //靜態方法只能引用靜態的屬性和方法
}
public void study(){
printSS();
System.out.println(name+"在學習");
}
public void sayHello(String sname){
System.out.println(name+"向"+sname+"說:你好!");
}
}
public class Test {
public static void main(String[] args) {
Student.ss = 323;//不用new,直接拿來用即可
Student.printSS();
Student s1 = new Student();
}
}
分析上圖可以得到以下結論:1,static變量和方法一旦產生便只存在於方法區中,不會存在於對象堆中,它從屬於類而和new出來的具體對象無關。2,由於它只產生於方法區中,那麼在靜態方法裏面只能調用靜態方法和變量(因爲它沒有訪問對象堆的能力,自然也就無法調用實例變量和方法了)。3,由於非靜態方法每一次執行都要加載類所在的方法區,會連同裏面的static變量和方法一起加載,所以非靜態方法和變量可以調用static變量和方法。
好了,關於static的內容就介紹這麼多了,下面開始介紹this:
this關鍵字是一個隱式參數,每個方法(static除外)都有隱式參數的自動傳參,不用寫出來也會自動傳,傳this的時候傳的是本身的對象(這是由於new出來的n個對象都共享同一段方法區的代碼,如果不用this指明當前調用方法的對象則會引起混亂)。
public class Student {
String name;
int id;
public Student(String name,int id){
this(name); //通過this調用其他構造方法,必須位於第一句! Constructor call must be the first statement in a constructor
this.name = name;
this.id = id;
}
public Student(String name){
this.name = name;
}
public Student(){
System.out.println("構造一個對象");
}
public void setName(String name){
this.name = name;
}
public void study(){
this.name= "張三";
System.out.println(name+"在學習");
}
public void sayHello(String sname){
System.out.println(name+"向"+sname+"說:你好!");
}
}
好了,本篇到此結束。小小地恭喜自己博客寫到了十篇,雖然訪問量寥寥無幾,但是我還是會繼續堅持地寫下去,積少成多,最終讓自己和看到我博客的人都有或多或少的收穫。