java几个容易出错的小程序

把基本知识过了一遍,发现了几个自己容易 出错的小程序,记录下来。。。。

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);      }    }  }

运行结果:

123public 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的方法。

记录沿途的心情。那样的生活才是我想要的。

java几个容易出错的小程序

相关文章:

你感兴趣的文章:

标签云: