类之谜:

类之谜:

一、令人混淆的构造器

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-11 23:35 77 阅读(129) 评论(0)  编辑  收藏


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


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(12)

随笔分类

随笔档案

文章分类

文章档案

新闻档案

相册

API文档

java开发与研究

にほん

上海房产

东京生活

数据库大全

编程与开发

美国开发生活

走向管理

搜索

最新评论

阅读排行榜

评论排行榜