Java 习题 (59)

题目:
从Detergent中继承产生一个新的类。覆盖scrub() 并添加一个名为sterilize() 的新方法。

解答:
先把Detergent类库代码放出来:

class Cleanser {
	private String s = "Cleanser";

    public void append(String a) {
        s += a;
    }

    public void dilute() {
        append(" dilute() ");
    }

    public void apply() {
        append (" apply() ");
    }

    public void scrub() {
        append( "scrub() ");
    }

    public String toString() {
        return s;
    }

    public static void main(String[] args) {
        Cleanser x = new Cleanser();
        x.dilute(); x.apply(); x.scrub();
        System.out.println(x);
    }
}

public class Detergent extends Cleanser {
	 public void scrub() {
        append(" Detergent.scrub() ");
        super.scrub();
    }

    public void foam() {
        append(" foam() ");
    }
	
	public static void main(String[] args) {
		Detergent x = new Detergent();
		x.dilute();
		x.apply();
		x.scrub();
		x.foam();
		System.out.println(x);
		System.out.println(“Testing base class: ”);
		Cleanser.main(args);
	}
}

根据上面的代码,来完成题目给的要求

package seven.Two;

class Cleanser {
    private String s = "Cleanser";

    public void append(String a) {
        s += a;
    }

    public void dilute() {
        append(" dilute() ");
    }

    public void apply() {
        append (" apply() ");
    }

    public void scrub() {
        append( "scrub() ");
    }

    public String toString() {
        return s;
    }

    public static void main(String[] args) {
        Cleanser x = new Cleanser();
        x.dilute(); x.apply(); x.scrub();
        System.out.println(x);
    }
}

class Detergent extends Cleanser {
    public void scrub() {
        append(" Detergent.scrub() ");
        super.scrub();
    }

    public void foam() {
        append(" foam() ");
    }
}

class NewDetergent extends Detergent {
    public void scrub() {
        append(" NewDetergent.scrub() ");
        super.scrub();
    }

    public void sterilize() {
        append(" sterilize() ");
    }
}

public class exerciseTwo{
   public static void main(String[] args) {
       NewDetergent nd = new NewDetergent();
       nd.apply();
       nd.dilute();
       nd.scrub();
       nd.foam();
       nd.sterilize();
       System.out.println(nd);
   }
}

结果如下:
在这里插入图片描述
如果觉得不错,就用点赞或者关注或者留言,来代替五星好评~
谢谢各位~

©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页