Example 11:
注意length和length()的用法:比如String str="My name is wuyangping"求长度为str.length();但String [] str=new String[5],求这个的长度为str.length.
Example 12:
在java1.5版本里面也支持像C语言里面的输出输入格式。比如System.out.printf("PI is approximately %f and E is approximately %b" , Math.PI,Math.E);
输出的结果为:PI is approximately 3.141593 and E is approximately true
Example 12:
public class Beat {
Integer i; //line 2
int x;
public Beat(int y) {
x = i + y; //line 5
System.out.println(x);
}
public static void main(String[] args) {
new Beat(new Integer(4)); //line 9
}
}
Line 2中的i编译的时候出现nullPointException异常,改为Integer i==new Integer(1)就行。
Example 13:
这里进入了物件导向设计。考题从第9章开始就迅速加深难度,之后各章节考题的量也开始增多了。遇到继承或多型的考题,在解题时务必:
Step01: 依程式大致画出类别图。
Step02: 检查父类别有无提供无参数建构子,若没有无参数建构子,子类别应
在建构子中的第1行呼叫super(⋯)或this(...)。若没有呼叫super(⋯) 或
this(...),应该就会编译失败了!
Step03: 检查覆盖方法有无符合规则(参考《第9-4节:覆盖方法》)。
Step04: 检查是否运用了多型(用上层型别宣告的变数或参数,来参考下层类别
建立的物件)。若是运用多型,注意呼叫到的方法有无被子类别覆盖。
Step05: 若程式中有转型,检查会不会出现执行时期错误。
这样解题或检视程式,应该就能取得结果。
Example 14:
JavaBean的命名规则是setXXX(),getXXX();isXXX();
Example 15:
class Foo{
public int a = 3;
public void addFive(){ a += 5; System.out.print("f "); }
}
class Bar extends Foo{
public int a = 8;
public void addFive(){this.a += 5; System.out.print("b ");}
}
public class Person{
public static void main(String d[]) {
Foo f = new Bar();
f.addFive();
System.out.println(f. a);
}
}
The output is b 3。f. A调用的是父类的方法。