java 接口与异常

一、   接口

接口的定义:

public interface Pet{

    public abstract void beFriendly();

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

}

接口的实现:

public class Dog extends Canine implements Pet{ // 关键词implement后跟接口名称

public abstract void beFriendly(){…}

    public abstract void play(){…}

 

    public void roam(){…}

    public viod eat(){…}

}

可以使用super关键词去调用父类的方法

 

二、   静态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,常量命名全部用大写字母

 

三、   Primitive主数据类型的包装

当你需要以对象的方式来处理primitive主数据类型时,就把它包装起来。

包装类:Boolean、Character、Byte、Short、Integer、Long、Float、Double

包装值:

int i = 288;

Integer iWrap = new Integer(i);

解开包装:

int unwrapped = iWrap.intValue();

 

四、   格式化输出

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

 

五、   静态的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));

}

}

 

六、   异常处理

把有风险的程序放在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掉来避开。

 

posted @ 2017-03-12 17:22  farmerspring  阅读(790)  评论(0编辑  收藏  举报