当前位置: 代码迷 >> J2SE >> 请问继承和组合的两个有关问题
  详细解决方案

请问继承和组合的两个有关问题

热度:4   发布时间:2016-04-24 14:05:59.0
请教继承和组合的两个问题
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();
}
------解决方案--------------------
  相关解决方案