学习笔记8(有些疑惑)

来源:互联网 发布:变年轻的软件 编辑:程序博客网 时间:2024/06/05 01:59
学习java依旧在缓慢的进行中,但是一步一个脚印总有其巨大的意义在其中,每每将已经学过的内容再看一遍,总能发现自己已经遗忘的,或者没有理解透彻的部分还有不少。
早上的课程上到了this关键字的运用,金星老师在课堂上布置了一道简单的饲养员养殖动物的题,当然并没有伸展到继承等的部分,只是在这个题目中熟悉this的一些常见的用法,我觉得受益良多,再做一遍,也确实体验到了this用法的方便之处:

class Tiger{
 Animal_Feeder f;
 Tiger(){                                           
  System.out.println("养老虎");
 }
 Tiger(Animal_Feeder f){                    
  this();                          //this的用法一,作为已有构造函数的调用
  this.f=f;                       //this的用法二,作为避免参数名相同而造成的冲突
 }
 void callForFood(){
  System.out.println("老虎说:要吃肉");
  f.feed(this);              //this的用法三,作为参数来传递
 }
}

class Rabbit{
 Animal_Feeder f;
 Rabbit(){
  System.out.println("养兔子");
 }
 Rabbit(Animal_Feeder f){
  this();             //用法一
  this.f=f;            //用法二
 }
 void callForFood(){
  System.out.println("兔子说:要吃草");
  f.feed(this);         //用法三
 }
}

public class Animal_Feeder {
public static void feed(Tiger f){
 System.out.println("饲养员喂老虎吃肉");
}
public static void feed(Rabbit f){
 System.out.println("饲养员喂兔子吃草");
}

public static void main(String[] args){
 Animal_Feeder feeder=new Animal_Feeder();
 new Tiger(feeder).callForFood();
 new Rabbit(feeder).callForFood();
}
}

结果:
养老虎
老虎说:要吃肉
饲养员喂老虎吃肉
养兔子
兔子说:要吃草
饲养员喂兔子吃草
 
其实等学习了继承和接口,这段代码还可以更进一步的完善,比如定义animal类,让兔子,老虎等动物继承该类。
 
另外,继续学习了finalize的部分内容(对象终结条件的验证),比如简单的可能的使用方式:针对thinking in java这本书上89页的练习12,对象被清理时tank是空状态:
我们进行了练习:
class Tank{
 boolean full=true;
 
 public Tank(boolean whether_is_full){
  full=whether_is_full;
 }
 
 void toEmpty(){
  full=false;
 }
 protected void finalize(){
  
  if(full)
   System.out.println("ERROR:It's full!");
  else
   System.out.println("Proper clean up!");
 }
}
public class Use_Tank {
 public static void main(String[] args){
  //Tank tank=new Tank(true);  
  //tank.toEmpty();
  //System.gc();     这几句没有结果出来,因为tank未被定为未用对象
  new Tank(true); 
  System.gc();   //运行垃圾回收器,来回收未用对象
  new Tank(true).toEmpty();
  System.gc(); 
 }
}
 
结果:
ERROR:It's full!                                                                      Proper clean up!
Proper clean up!  奇怪的是,在多次运行后,总会出现那么一次答案变为ERROR:It's full! 没想明白这是为什么?
哪位牛人帮我解答下。。。(cmd里面不会出现这个问题,eclipse会出现这个问题!)
原创粉丝点击