类之谜:
一、令人混淆的构造器
package com.huihui.text;
public class Confusing {
private Confusing(Object o){
System.out.print("object");
}
private Confusing(double[] a){
System.out.print("double");
}
public static void main(String args[]){
new Confusing(null);
}
}
输出;
double
解释:精确性问题
二、狸猫换太子
package com.huihui.text;
public class Counter {
private static int count;
public static void increament(){
count++;
}
/**
* @return Returns the count.
*/
public static int getCount() {
return count;
}
}
package com.huihui.text;
public class Dog extends Counter {
public void woof(){
increament();
}
// public static void main(String args[]){
// Dog d=new Dog();
// d.increament();
// }
}
package com.huihui.text;
public class Cat extends Counter {
public void meow() {
increament();
}
}
package com.huihui.text;
public class Test {
public static void main(String args[]) {
Dog[] dogs = { new Dog(), new Dog() };
for (int i = 0; i < dogs.length; i++) {
dogs[i].woof();
}
Cat[] cats = { new Cat(), new Cat(), new Cat() };
for (int i = 0; i < cats.length; i++) {
cats[i].meow();
}
System.out.print(Dog.getCount());
}
}
输出:5
解释:每一个静态域在声明他的类中及所有子类中共享一份单一的拷贝
但你拿不准是,优先选择组合而不是继承