Java學習之路(四)

來源:互聯網
上載者:User

標籤:

1:static關鍵字

靜態變數可以使用類名來調用 也可以使用對象來調用

但是同一個類的同一個靜態變數儲存的位置是一樣的 

所以無論改變那個對象的靜態變數的值其他對象的同一個變數的值也會改變

 

靜態函數中使用的變數必須是靜態 

可以這樣理解

靜態函數中若使用的非靜態變數的話   相當於this.變數  而這裡的this就不明確了

 

靜態代碼塊在類裝載的時候執行  

為了給類中的靜態變數賦值

 2:繼承

子類可以繼承父類的成員變數和成員函數   不會繼承建構函式

 

當執行個體化一個子類對象時   必須會調用父類的建構函式  而且必須先調用父類的建構函式     我們也可以在子類的建構函式裡使用super函數  super也必須為第一個函數

 

super的作用:可以避免寫重複的代碼

 

一個簡單的繼承

Persion類:

class Persion{    String name;    int age;        Persion(){        System.out.println("Persion無參建構函式");    }        Persion(String name , int age){        this.name = name;        this.age = age;        System.out.println("Persion有參建構函式");    }        void eat(){        System.out.println("吃飯");    }    }

 

Student類:

class Student extends Persion{    int grade;        Student()    {        System.out.println("Student無參建構函式");    }    Student(String name,int age,int grade )    {        this.grade = grade;        //this.age = age;        //this.name= name;        System.out.println("Student有參參建構函式");    }}

 

 

主函數:

 class Text{     public static void main(String args[])     {        Student aStudent = new Student("李鵬",2,3);        System.out.println(aStudent.name);        System.out.println(aStudent.age);        System.out.println(aStudent.grade);     } }

 

 

 結果:

可見當參數為3個  會先調用父類的無參建構函式 然後是子類的3個參數的建構函式  所以這樣的話:如果子類沒有給父類的變數賦值  父類變數是不會被賦值的  所以子類必須為父類變數賦值

①可以直接在子類為父類變數賦值

②可以調用super方法為來調用父類建構函式

修改後的Student類:

class Student extends Persion{    int grade;        Student()    {        System.out.println("Student無參建構函式");    }    Student(String name,int age,int grade )    {        super(name,age);        this.grade = grade;        //this.age = age;        //this.grade = grade;        System.out.println("Student有參參建構函式");    }}

 

運行結果:

 

這樣便可以使代碼盡量的減少

 

Java學習之路(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.