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




  • 相关阅读:
    Visio2019专业版激活方法
    I2C总线协议
    latch-up和Antenna-effect
    读--数字集成电路物理设计
    数字IC设计流程与工具
    读--FPGA设计指导原则
    读--数字集成电路设计与实现
    FIFO
    半导体存储器
    触发器
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10718974.html
Copyright © 2020-2023  润新知