• java几个easy出错的小程序


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

    。。。

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




  • 相关阅读:
    C# 文件重命名
    C# 获取图像文件
    我开通了博客
    C# 图像截取
    C# 从txt读取内容
    Linux 下查看用户组信息
    部署Jenkins完整记录
    一篇文章搞定Java注解^_^
    Java基础之接口
    枚举让盗版美国总统wcc给你整明白哈哈
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10063209.html
Copyright © 2020-2023  润新知