本章節目標:
理解構造方法以及重載機制,通過構造方法可以完成對象的創建,并且能夠通過引用訪問對象的內存,了解Java虛擬機內存管理,能夠畫出程序執行過程的內存圖,并了解空指針異常是如何發生的,以及方法調用時參數是如何傳遞的。
Java對象的創建和使用方法
類定義之后,就可以使用類這個“模板”來創造“對象”了,一個類是可以創建多個對象的哦!怎么創建呢,語法是什么?其實語法格式很簡單:new 類名(),這樣就可以完成對象的創建了。俗話說,你想要什么java都可以給你,想要啥你就new啥。請看下面代碼:
public class StudentTest {
public static void main(String[] args) {
//創建一個學生對象
new Student();
//再創建一個學生對象
new Student();
}
}
為了使用對象更加方便,建議使用變量接收一下?例如以下代碼:
public class StudentTest {
public static void main(String[] args) {
//創建一個學生對象
Student s1 = new Student();
//再創建一個學生對象
Student s2 = new Student();
//以上代碼其實和這行代碼差不多
int i = 10;
}
}
以上代碼最初接觸的時候,大家肯定會感覺非常陌生,這也是正常的,Student s1 = new Student()實際上和int i = 10是類似的,對于int i = 10來說,int是一種基本數據類型,i是變量名,10是int類型的字面量。那對于Student s1 = new Student()來說,其中Student是一種引用數據類型,s1是變量名,new Student()執行之后是一個Student類型的對象。
大家要注意了,java語言當中凡是使用class關鍵字定義的類都屬于引用數據類型,類名本身就是這種引用數據類型的類型名。創建了對象之后怎么去訪問這個對象的屬性呢,或者說學生對象現在有了,怎么去訪問他的學號、姓名、性別、年齡等信息呢。請看以下代碼:
public class StudentTest {
public static void main(String[] args) {
//創建一個學生對象
Student s1 = new Student();
//再創建一個學生對象
Student s2 = new Student();
//以上代碼其實和這行代碼差不多
int i = 10;
int no1 = s1.no;
System.out.println("學號:" + no1);
String name1 = s1.name;
System.out.println("姓名:" + name1);
int age1 = s1.age;
System.out.println("年齡:" + age1);
boolean sex1 = s1.sex;
System.out.println("性別:" + sex1);
int no2 = s2.no;
System.out.println("學號:" + no2);
String name2 = s2.name;
System.out.println("姓名:" + name2);
int age2 = s2.age;
System.out.println("年齡:" + age2);
boolean sex2 = s2.sex;
System.out.println("性別:" + sex2);
//當然,也可以不使用no1,no2這樣的變量接收
System.out.println("學號 = " + s1.no);
System.out.println("姓名 = " + s1.name);
System.out.println("年齡 = " + s1.age);
System.out.println("性別 = " + s1.sex);
System.out.println("學號 = " + s2.no);
System.out.println("姓名 = " + s2.name);
System.out.println("年齡 = " + s2.age);
System.out.println("性別 = " + s2.sex);
}
}
運行結果如下圖所示:
圖9-1:對象的創建和使用
接下來解釋一下以上的輸出結果,通過以上的Student類可以創建很多學生對象,假設通過Student類實例化了兩個學生對象,那必然會有兩個不同的學號,以上程序中并沒有給學號賦值,但是獲取了到的學號都是0,這是怎么回事呢?這是因為在java語言當中,當實例變量沒有手動賦值,在創建對象的時候,也就是說在new的時候,系統會對實例變量默認賦值,它們的默認值請參考下表:
數據類型 |
默認值 |
byte |
0 |
short |
0 |
int |
0 |
long |
0L |
float |
0.0f |
double |
0.0 |
boolean |
false |
char |
\u0000 |
引用類型 |
null |