seaairland

 

类之谜

类之谜:

一、令人混淆的构造器

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

解释:每一个静态域在声明他的类中及所有子类中共享一份单一的拷贝

但你拿不准是,优先选择组合而不是继承

 

 

posted on 2006-04-07 16:34 chenhui 阅读(173) 评论(0)  编辑  收藏 所属分类: java基础


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

文章分类

文章档案

介绍 IOC

友情链接

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜