java子類實例化過程

class Person{

   String name;

   int age;

/*

以上兩個爲成員變量

*/

   Person(){

   System.out.println("Person的無參數構造函數");

   }

   Person(String name,int age){

   this.name = name;

   this.age= age;

   //System.out.println("my name is " + name + "  \n my age is " + age );

   }

   //以上兩個Person爲構造函數

   void eat(){

   System.out.println("吃飯");

   }

   //void爲成員函數

}


----

/* extend只能繼承成員變量和成員函數而不能繼承Persong中的構造函數


在子類中必須調用父類中的構造函數,如果不調用則系統自行輔助調用

即直接加上一句話

super進行調用   ---super 如果調用不爲空的構造函數則super()不執行

如果想調用父類中其他的任意函數,那麼就在super()括號中寫上需要調用的參數即可

*/

class Student extends Person{

   int grade;

   //在子類的構造函數中,必須 調用父類的構造函數  爲什麼????

   Student(){

   //super();

   System.out.println("Student的無參數構造函數");

   }

   Student(String name , int age , int grade){

   //this.name = name;

   //this.age = age;

   super(name,age);

   this.grade = grade;

   System.out.println("my name is " + name + "  \n my age is " + age  + "  my grade is "     + grade);

   }

}


--------

class Test{

   public static void main (String args []){

   Student student = new Student("張三",18,3);

   System.out.println(student.name);

   System.out.println(student.age);

   System.out.println(student.grade);

/*生成Student這個類的對象,

首先我們使用new這個關鍵字調用Student這個構造函數

當我們使用new這個關鍵字來調用student這個構造函數時候,

有一個東西會幫我們先調用Person這個函數的無參數構造函數

然後在執行Student student = new Student();

*/

   }

}

wKiom1MKv8ugea4_AAEUIic4jQc135.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章