java易忽略點

switch關鍵字

在switch關鍵字的使用中,表達式的類型只能爲byte、short、char和int這4種之一。
每當一個條件結束,要加入break關鍵字,常用的用法:

public class demo15
{
	public static void main(String args[]){
		int j=2; 
		switch(j){ 
			case 2: 
				System.out.println("Value is two.");
				break;
			case 3: 
				System.out.println("Value is two.");
				break;
			default: 
				System.out.println("Value is "+j);
				break;
			}
	}
}

程序理所當然的會打印Value is two.但是看以下的代碼:

public class demo15
{
	public static void main(String args[]){
		int j=2; 
		switch(j){ 
			case 2: 
				System.out.println("Value is two.");
				//break;
			case 3: 
				System.out.println("Value is three.");
				break;
			default: 
				System.out.println("Value is "+j);
				break;
			}
	}
}

現在則會打印Value is two.   Value is three.
再看以下代碼:

public class demo15
{
	public static void main(String args[]){
		int j=2; 
		switch(j){ 
			case 2: 
				System.out.println("Value is two.");
				//break;
			case 3: 
				System.out.println("Value is three.");
				//break;
			default: 
				System.out.println("Value is "+j);
				//break;
			}
	}
}

程序打印:Value is two.    Value is three.    Value is 2
綜上所述:java中switch判斷語句只要是沒有遇到break,則不管條件是否成立都會執行,直到遇到break時,程序纔會結束。

 
 
在類的繼承關係中,屬性不會被繼承,但是子類具有父類的方法,如以下代碼:
class A
{
    int i=1;
	public void fun(){
		System.out.println("A-->fun()方法");
	};
	public void fun1(){
		System.out.println("A-->fun1()方法");
	}
}
class B extends A
{
	int i=2;
	public void fun(){
		System.out.println("B--fun()方法");
	}
}
public class NumberFormatDemo02
{
	public static void main(String args[]){	
		A a=new	B();
		a.fun();	//調用的是子類中覆寫的fun()方法
		System.out.println(a.i);	//父類A中的i屬性 不會訪問子類 如果父類沒有此屬性 會出錯
		B b=new B();	
		b.fun1();	//雖然在子類B中沒有定義此方法,但是會向父類中查找
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章