java初始化和清除

來源:互聯網
上載者:User

1、構造器初始化

new一個對象首先會給器分配一塊記憶體,並且調用構造方法進行初始化。

構造方法:構造方法與類型一致,且沒有傳回型別。每個類都有一個預設的構造方法。

構造方法和普通方法一樣可以重載,用於傳入不同的參數。區分構造方法,只能由參數個數不同,類型不同去區分。

public class Contruct {Contruct() {//無參構造方法System.out.println("構造器");}Contruct(int i){//有參構造方法System.out.println("構造器:"+i);}Contruct(double s){System.out.println("構造器:"+s);}public void Contruct(int i){//普通方法(非構造方法)System.out.println("非構造方法");}}



2、 成員初始化

類的成員變數,基本類型預設初始化,對象需要手動將其初始化,免得使用的時候會報錯。

局部成員變數需要初始化,包括基本類型,否則編譯報錯。

static方法內,不能直接引用非是static變數和方法。

public class TestMain {int j;static int k;//類的成員變數,預設初始化為0public static void main(String[] args) {TestMain t;for(int i=0; i<j; i++){//Cannot make a static reference to the non-static field jt.f();//The local variable t may not have been initializednew Contruct();new Contruct(i);System.out.println("k:"+k);//k:0}}public void f(){int m;//局部變數System.out.println(j);//j非局部變數,預設初始化值為0System.out.println(m);//The local variable m may not have been initialized}}

3、數組初始化

數組初始化的方法:

1、靜態初始化:int[] a1 = {1,2,3,4,5};

2、動態初始化: 先聲明int[] a2; for(){a2[i]};

3、建立數組對象,預設初始化int[] a3 = new int[];

public class ArrayTest {public static void main(String[] args) {int[] a1 = {1,2,3,4,5};//(1)靜態初始化int[] a2;//聲明int[] a3 = new int[5];//(2)建立數組對象,預設初始化為0a2 = a1;//引用的賦值for(int i=0; i<a2.length; i++){a2[i]++;//(3)動態初始化}for(int j=0; j<a1.length; j++){prin("a1["+j+"]:"+a1[j]);}for(int k=0; k<a3.length; k++){prin("a3["+k+"]:"+a3[k]);}}static void prin(String s){System.out.println(s);}}



3、清除

GC:JVM記憶體回收機制,回收new出來的記憶體,只針對記憶體回收,當對象的不再使用的時候自動調用。


final、finally、finalize的區別

final:定義屬性、方法和類。定義的屬性不可改變;定義的方法不可重寫;定義的類不可繼承。

finally:異常處理語句的一部分,表示總是執行try{}catch{}finally{}

finalize:在記憶體回收的時候調用被回收對象的此方法,用於記憶體回收。





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.