JAVA基礎(第12天 拆裝箱)

package com.wdzl.demo07;

public class TestPack {
	public static void main(String[] args) {
		//裝箱
		int a =1;
		Integer a1 = new Integer(a);
		Integer a2 = Integer.valueOf(a);
		Integer a3 = Integer.valueOf(1);
		Integer a4 = Integer.valueOf(a+"");
		Integer a5 = Integer.valueOf(""+a);
		
		System.out.println("a:"+a);
		System.out.println("a1:"+a1);
		System.out.println("a2:"+a2);
		System.out.println("a3:"+a3);
		System.out.println("a4:"+a4);
		System.out.println("a5:"+a5);
		//拆箱
		Integer a6 = Integer.valueOf(1);
		int a7 = a6.intValue();
		System.out.println("a7:"+a7);
		
		System.out.println("****************");
		//自動裝箱
		Integer a8 = a7;
		System.out.println("a8:"+a8);
		//判斷它們的地址或值是否相等
		System.out.println(a1==a2);
		System.out.println(a1.equals(a2));
		System.out.println(a2==a3);
		System.out.println(a2.equals(a3));
		System.out.println(a3==a4);
		System.out.println(a3.equals(a4));
		System.out.println(a4==a5);
		System.out.println(a4.equals(a5));
		System.out.println(a6==a7);
		System.out.println(a6.equals(a7));
	}
}

在這裏插入圖片描述在這裏插入圖片描述


throw 和 throws

  • throws用於方法聲明,聲明方法中可能拋出的異常類型,後面可以跟多個異常類
  • throw 用於方法中拋出異常對象,只能是一個異常對象

 package com.wdzl.demo02;
/**
 * throw 和 throws
 *	throws用於方法聲明,聲明方法中可能拋出的異常類型,後面可以跟多個異常類
 *  throw 用於方法中拋出異常對象,只能是一個異常對象
 */
public class Test {
	public static void setAge(int age) throws AgeException,ClassNotFoundException {
		if(age<18 || age>100) {
			//拋出異常對象
			AgeException e = new AgeException("年齡只能在18~100之間");
//			System.out.println(e.hashCode());
			throw e;
		}
		int aa = age;
		System.out.println("*******"+aa);
	}
	public static void main(String[] args) {
		try {
			setAge(-19);
		} catch (AgeException | ClassNotFoundException e) {
			e.printStackTrace();
//			System.out.println(e.hashCode());
			System.out.println("異常信息:"+e.getMessage());
		}
//		System.out.println("程序結束!");
	}
	
	
}
package com.wdzl.demo02;
/**
 * 自定義異常
 * 繼承Exception類
 */
public class AgeException extends Exception {
	public AgeException(String msg) {
		super(msg);
		System.out.println("年齡異常了!");
	}
	
	public AgeException() {
		super("%%%%%%年齡異常了%%%%%");
	}
	@Override
	public String getMessage() {
		System.out.println("------");
		return "***"+super.getMessage()+"***";
	}
	
}

運行結果:
在這裏插入圖片描述


重寫(兩大一小)

  • 一大:子類重寫的訪問權限修飾符大於等於父類
  • 二小:
    • 重寫的子類的返回值類型小於等於父類
    • 重寫的子類的異常類型小於等於父類

處理異常與運行時異常

  • RuntimeException:運行時異常編譯階段,不需要強制進行檢查處理的異常
  • 處理異常:編譯階段,就需要對異常進行拋出。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章