java幾個容易出錯的小程式
阿新 • • 發佈:2019-02-20
把基本知識過了一遍,發現了幾個自己容易 出錯的小程式,記錄下來。。。。
1,關於try-catch異常
2,JAVA中的自省機制
3,有繼承關係的類中靜態函式
1,關於try-catch異常
package chapter5; public class p101 { public static void main(String args[]) { int a[]=new int[3]; try{ a[0]=1; a[1]=2; a[2]=3; a[3]=3/0; }catch(ArrayIndexOutOfBoundsException e) { System.out.println("index out of bounds!"); e.printStackTrace(); }catch(ArithmeticException e) { System.out.println("divided by zero!"); } } }
輸出結果為:divided by zero!
首先執行的是:賦值語句右邊的3/0;所以捕獲的是 ArithmeticException異常
2,java中的自省機制
自省是軟體分析自己的能力,這個能力由java.lang.reflect包中的類和介面提供。
為了實現自省操作,還有一個類必須使用,即Class類, Class 類定義在java.lang包中,Class類沒有public的建構函式,java虛擬機器會構建Class物件,通過forName方法可以獲得這個物件。
自省功能不僅可以獲得系統自帶的類的各種資訊(Class c=Class.forName("java.lang.Class"); 也可以獲得程式設計師自己定義的類的各種資訊。
package chapter12; import java.lang.reflect.*; class myc{ public int x,y; public myc() { x=y=0; } public myc(int a,int b) { x=a;y=b; } } public class p275 { public static void main(String args[]) { try{ System.out.println("123"); myc a=new myc(); Class c=a.getClass(); Constructor con[]=c.getConstructors(); for(int i=0;i<con.length;i++) System.out.println(con[i]); } catch(Exception e) { System.out.println("Exception"+e); } } }
執行結果:
123
public chapter12.myc()
public chapter12.myc(int,int)
3,程式的輸出結果:
public class p37_1 {
public static void main(String args[]){
Father father=new Father();
Father child=new Child();
System.out.println(father.getName());
System.out.println(child.getName());
}
}
class Father{
public static String getName(){
return "father";
}
}
class Child extends Father{
public static String getName(){
return "son";
}
}
輸出:
Father Father
這兩個getName方法時靜態方法,所以在記憶體中的地址是固定的,根本不存在衝突的問題。具體執行哪一個,要看是由哪個類來呼叫的,因為是靜態方法,而且兩個引用都是father的,所以只會呼叫father的方法。