Chapter 1 General Techniques
01> Java中的参数都是 By value传递而并非 By reference
--- By references误解源于 [所有 Java objects 都是Object reference] 这一事实.
对于Primitive type data传递给方法的是变量的复本, 她在方法内改变而原值不变;
对于 Object 传递给方法的是 Object reference 的复本, 即对象引用的复本.
Example: Point p = new Point(0,0); 其中 p 是一个 Object reference,
当 p 以 p2 作为参数传递时, 因为传递的是引用, 故两者指向同一个对象!!
--- p2 即 p(Object reference) 的复本.
02> 对不变的data 和 Object references 使用 final
对于Primitive type data: || static final int someIne = 10;
//任何修改 someInt 的尝试都无法通过编译.
对于Object: || final 限制的是对象的引用, 即这个引用变量只能指向同一个对象.
--> final 修饰的是变量 wheel, 故wheel是final的,亦即 Immutable, 永远指向同一个对象!
而wheel这个引用所指向的 Heap 上某一个内存地址, 即wheel所指的对象不受final 限制, 是 Mutalbe 的.
Example: private static final Circle wheel = new Circle(5.0);
//final wheel reference to object ->Circle(5.0);
wheel.setRadius(7.5);
//Object values is 7.5 now, wheel still reference to the same object.
03> 缺省情况下所有的 non-static 方法都可被覆盖!
缺省情况下, classes拥有的任何 non-private / non-static 方法都允许被 subclasses 覆盖.
除非使用 final声明.
这个特性的重要性表现: **class设计和 ** 运行期性能(Runtime Performance)
Declare 类为final, 亦即声明了这个class的所有方法为final, 这个class不能有subclass.
04> 在arrays 和Vectors之间慎重选择
Java中的数组有下标检查 ------- ArrayIndexOutOfBoundsException
数组的容量 ----- Array对象的public 变量 length.
Array可以容纳 primitive Types 和 Object references;
primitivetypes: 当新建一个array对象时, 每一个元素都依据其types而被赋缺省值;
Object references: 此时Java将其初值设为 null.
Vector 容量可以自动增长, 当有元素删除时也会相应的变化;
Vector 提供size() 方法获得当前实际的元素个数.
05, 06> 多态 (Polymorphics) 优于 instanceof
instanceof 操作符在运行期确定 [某个对象属于那个class] 的机制. ----Dynamic type
程序中应尽量使用多态替代instanceof!!
Example:
interface Employee{ public int salary(); pubic int bonus(); }
class Manager implements Employee{
private static final int mgrSal = 40000;
private static final int mgrBonus = 0;
public int salary() { return mgrSal; }
public int bonus() { return mgrBonus; } }
class Programmer implements Employee{
private static final int prgSal = 50000;
private static final int prgBonus = 10000;
public int salary() { return mgrSal; }
public int bonus() { return mgrBonus; } }
class Payroll{
pubic int calcPayroll(Employee emp){
//Calculate the bonus. No instanceof check needed!!!!!
return emp.salary() + emp.bonus();
}
public static void main(String []args){
Payroll pr = new Payroll();
Programmer prg = new Programmer();
Manager mgr = new Manager();
System.out.println(pr.calcPayroll(prg) ); //&&&&&&&&& Polymorphics 的实现!!
System.out.println(pr.calcPayroll(mgr) );
}
}
07> 一旦不再需要object references ,就将其设为 null
Java garbage collection负责回收不再被使用的内存. 虽然有 gc, 但
内存在程序中如何被运用,仍然是只得关注的议题.