java 接口與異常

1、   接口java

接口的定義:app

public interface Pet{dom

    public abstract void beFriendly();orm

    public abstract void play();   //接口的方法必定是抽象的對象

}繼承

接口的實現:接口

public class Dog extends Canine implements Pet{ // 關鍵詞implement後跟接口名稱ci

public abstract void beFriendly(){…}it

    public abstract void play(){…}io

 

    public void roam(){…}

    public viod eat(){…}

}

可使用super關鍵詞去調用父類的方法

 

2、   靜態final變量

一個被標記爲final的變量表明它一旦被初始化後就不會改動。 

final int size = 3; //size的值沒法改變

靜態final變量的初始化:

public class Foo{

    public static final int FOO_X = 25;

}

public class Bar{

    public static final double BAR_SIGN;

    static{

    BAR_SIGN = (double) Math.random();

}

}

Final的變量表明你不能改變它的值

Final的method表明你不能覆蓋掉該method

Final的類表明你不能繼承該類

Java中的常量是把變量同時標記爲static和final,常量命名所有用大寫字母

 

3、   Primitive主數據類型的包裝

當你須要以對象的方式來處理primitive主數據類型時,就把它包裝起來。

包裝類:Boolean、Character、Byte、Short、Integer、Long、Float、Double

包裝值:

int i = 288;

Integer iWrap = new Integer(i);

解開包裝:

int unwrapped = iWrap.intValue();

 

4、   格式化輸出

format("%,d",1000000000);  //1,000,000,000

format("I have %.2f bugs to fix.", 476578.09876);

 //I have 476578.10 bugs to fix.

 

%[argument number][flags][width][.precision]type

argument number:格式化的參數超過一個時,要在這裏指定是哪個

flags:特定類型的特定選項,例如數字要加逗號或者正負號

width:最小字符數,注意:這不是總數,輸出能夠超過此寬度,若不足則會主動補零

.precision:精確度

type:必定要指定類型參數

 

完整的日期和時間:%tc

String.format("%tc",new Date());  //Sun Nov 28 14:52:41 MST 2004

只有時間:%tr

String.format("%tr",new Date());  //03:01:46 PM

周、月、日:%tA %tB %td

Date today = new Date();

String.formate("%tA,%tB %td",today,today,today);

//Sunday,November 28

操做日期:使用java.util.Calendar

 

5、   靜態的import

import static java.lang.System.out;

import static java.lang.Math.*;

class WithStatic{

    public static void main(String [] args){

out.println("sqrt" + sqrt(2.0));

out.println("tan" + tan(60));

}

}

 

6、   異常處理

把有風險的程序放在try塊,用catch塊擺放異常情況的處理程序。

異常是一種Exception類型的對象,catch的參數是Exception類型的ex引用變量。

try{

    //危險動做

}catch(Exception ex){

    //嘗試恢復,在有拋出異常時執行

}

 

在編寫可能會拋出異常的方法時,必須聲明有異常

public void takeRisk()throw BadException{

    if(abandonAllHope){

    throw new BadException();

}

}

 

調用:

public void crossFingers(){

    try{

    anObject.takeRisk();

}catch(BadException ex){

    System.out.println("Aaargh!");

    ex.printStackTrace();

}

}

 

用final塊存放無論有沒有異常都要執行的程序。

有多個catch塊時要從小排到大。

若是不想處理異常,能夠把他duck掉來避開。

相關文章
相關標籤/搜索