日期:2014-05-20  浏览次数:20819 次

请教继承和组合的两个问题
import   com.bruceeckel.simpletest.*;
import   java.util.*;

class   Villain   {
    private   String   name;
    protected   void   set(String   nm)   {   name   =   nm;   }
    public   Villain(String   name)   {   this.name   =   name;   }
    public   String   toString()   {
        return   "I 'm   a   Villain   and   my   name   is   "   +   name;
    }
}

public   class   Orc   extends   Villain   {
    private   static   Test   monitor   =   new   Test();
    private   int   orcNumber;
    public   Orc(String   name,   int   orcNumber)   {
        super(name);
        this.orcNumber   =   orcNumber;
    }
    public   void   change(String   name,   int   orcNumber)   {
        set(name);   //   Available   because   it 's   protected
        this.orcNumber   =   orcNumber;
    }
    public   String   toString()   {
        return   "Orc   "   +   orcNumber   +   ":   "   +   super.toString();
    }
    public   static   void   main(String[]   args)   {
        Orc   orc   =   new   Orc( "Limburger ",   12);
        System.out.println(orc);
        orc.change( "Bob ",   19);
        System.out.println(orc);
        monitor.expect(new   String[]   {
            "Orc   12:   I 'm   a   Villain   and   my   name   is   Limburger ",
            "Orc   19:   I 'm   a   Villain   and   my   name   is   Bob "
        });
    }
}   ///:~

问题:
1. "Orc   12:   I 'm   a   Villain   and   my   name   is   Limburger "
    "Orc   19:   I 'm   a   Villain   and   my   name   is   Bob "
      这两个结果是怎么得到的?前一个 "Orc12: "更是不知怎样来的?
2.public   String   toString()   {
        return   "Orc   "   +   orcNumber   +   ":   "   +   super.toString();
    }
      这个字符类型有什么作用?

------解决方案--------------------
System.out.println(orc);
因为orc是一个对象,println会自动调用orc的toString()方法.
下面是几个关键的方法.

public void println(Object x) {
synchronized (this) {
print(x);
newLine();
}
}

public void print(Object obj) {
write(String.valueOf(obj));
}

public static String valueOf(Object obj) {
return (obj == null) ? "null " : obj.toString();
}
------解决方案--------------------