惊鸿人间一片 2021-03-18 11:33 采纳率: 25%
浏览 394
已采纳

如何在测试类中实现父类的toString方法的同时实现子类的toString方法?

最近在练习的时候添加了一个动物类父类

package com.拓展;

public class Animal {
    private  String name;
    private  int age;
    private String eat;
    private  boolean body;

    public Animal() {
    }

    public Animal(String name, int age, String eat, boolean body) {
        this.name = name;
        this.age = age;
        this.eat = eat;
        this.body = body;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEat() {
        return eat;
    }

    public void setEat(String eat) {
        this.eat = eat;
    }

    public boolean isBody() {
        return body;
    }

    public void setBody(boolean body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "这个动物的名字叫做" + name +
                ", 今年" + age +
                "岁, 分属于" + eat +
                "动物, 身体" + body1(body)+","
                ;
    }

    public  String body1(boolean body){
        if (body) {
            return ("健康");
        }
        return ("不健康");
    }
}

然后再创建了一个他的子类,但是子类会有一个新的功能,我想把这个功能添加到toString()中,如下:

package com.拓展;

public class Bird extends Animal{
    private String color;

    public  Bird(){}

    public Bird(String name, int age, String eat, boolean body, String color) {
        super(name, age, eat, body);
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return    " 颜色是"+color;
    }
}

然后我发现在测试类中无法通过调用toString方法来达到使用子类和父类中的toString(),我就使用了一个笨方法,但是我感觉这种代码太糟糕了,不知道有没有什么其他的方法

package com.拓展;
public class test2 {
    public static void main(String[] args) {
        Animal animal= new Animal("鹦鹉",2,"",true);
        Bird bird1= new Bird();
        bird1.setColor("黄白相间");
        System.out.print(animal.toString());
        System.out.println(bird1.toString());
    }
}

求大佬指点 

  • 写回答

3条回答 默认 最新

  • 开发者小峰 2021-03-18 11:45
    关注

    @Override

    public String toString() {

    return super.toString()+" 颜色是"+color;

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波