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

最近看的书上的一个题目,希望帮忙一下
编写一个抽象类Tag
Field:id(String类型),width(int类型),height(int类型),方法:String render()(抽象方法)
再定义类Td,要求继承于Tag类。在Td类中,包含Field:content(String类型)。Td类要求改写render方法,该方法用于输出一个td。例如,如果当前td的id为"td01",weidth=23,height=18,content="I'm a td object",render方法的返回结果应该为字符串 "<td id='td01' width=‘23’ height=‘18’ >I'm a td object</td>"
要求所有的Field必须是私有访问权限,并且有相应的get/set方法。如果某个属性没有设置,则该属性不出现。比如,如果没有设置width,则render方法的返回结果为: "<td id='td01' height=‘18’ >I'm a td object</td>" (注意width属性没有出现)
您还需要编写一个主程序来测试Tag和Td类。

我想知道红色的部分是怎么实现的

------解决方案--------------------
楼主说的这么详细分析这么清楚,那就按照思路写啊。。
Java code
package common;

public abstract class Tag {
    protected int id;
    protected int width;
    protected int height;

    public int getWidth() {
    return width;
    }

    public void setWidth(int width) {
    this.width = width;
    }

    public int getHeight() {
    return height;
    }

    public void setHeight(int height) {
    this.height = height;
    }

    public void setId(int id) {
    this.id = id;
    }

    public abstract void render();

    public int getId() {
    return id;
    }
}


package common;

public class Td extends Tag {
    private String content;

    public Td() {
    super();
    }

    public String getContent() {
    return content;
    }

    public void setContent(String content) {
    this.content = content;
    }

    @Override
    public void render() {
    StringBuffer sb = new StringBuffer("");
    sb.append("<td ");
    if (this.getId() != 0)
        sb.append(" id='" + this.getId() + "'");
    if (this.getWidth() != 0)
        sb.append(" width='" + this.getWidth() + "'");
    if (this.getHeight() != 0)
        sb.append(" height='" + this.getHeight() + "'");
    sb.append(">");
    if (this.getContent() != null)
        sb.append(this.getContent());
    sb.append("</td>");
    System.out.println(sb.toString());
    }

    public static void main(String args[]) {
    Td td = new Td();
    td.setWidth(22);
    td.setHeight(33);
    td.setContent("sdass");
    td.render();
    }
}