| Bean 的个人资料Anders.Pan的共享空间照片日志列表 | 帮助 |
|
|
8月20日 java pitfall
short a , b, c; a = 1; b = 2; c = a + b;//编译指示这行出错了,possible loss of precision
原因:二元操作符(如+、-、*、/)当其操作的对象是基本数据类型时,会把其操作的变量自动提升为至少到int型
class A { public void f1() { System.out.println("A.f1"); } }
class B extends A{ public int f1() { // 重复定义错误,f1()已经在父类A中定义,可以修正为void f1(),覆盖A的同名方法 System.out.println("B.f1"); return 0; }
}
public static void main(String arg[]) { A a = new B(); a.f1(); // 修正后,调用的是B的f1()方法 }
比如: Object a = null; int intValue = 0;
if (!a) { // 编译错误 ... }
while(!intValue); // 编译错误
class A { public int f1() { System.out.println("A.f1"); return 2; } }
class B extends A{ public int f1() { try { return 0; } catch (Exception e) { // TODO: handle exception } finally { System.out.println("B.f1"); return 1; } }
public static void main(String arg[]) { A a = new B(); System.out.println(a.f1()); }
结果是: B.f1 1
无论try块中发生了什么,只要不是vm关闭,机器关闭,finally中的语句始终被执行
return; int a = 1; // 编译错误,该句永远不会被执行
改为: if(true) return;
int a = 1; // 编译通过
public interface test() { int i = 0; // 被自动转换为static final }
|
|
|