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中没有定义此方法,但是会向父类中查找 } }