類之謎:
一、令人混淆的構造器
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
解釋:每一個靜態域在聲明他的類中及所有子類中共享一份單一的拷貝
但你拿不準是,優先選擇組合而不是繼承