Richmond1979 2010-06-29 15:49
浏览 175
已采纳

调用基类的构造函数

public class Animal {
public Animal(String aType) {
type = new String(aType);
}

public String toString() {
return "This is a " + type;
}

private String type;
}

public class Dog extends Animal {
public Dog(String aName) {
super("Dog");
name = aName;
breed = "Unknown";
}
public Dog(String aName, String aBreed) {
super("Dog");
name = aName;
breed = aBreed;
}

private String name;
private String breed;
}

public class TestBerived {
public static void main(String[] args) {
Dog aDog = new Dog("Fido", "Chihuahua");
Dog starDog = new Dog("Lassie");
System.out.println(aDog);
System.out.println(starDog);
}
}

输出结果是:
This is a Dog
This is a Dog

[size=x-small]请问调用基类的构造函数为何会隐含调用基类的toString方法呢?[/size]

  • 写回答

3条回答 默认 最新

  • weixin_42516107 2010-06-29 21:42
    关注

    [code="java"]
    public Dog(String aName) {
    super("Dog");
    name = aName;
    breed = "Unknown";
    }
    public Dog(String aName, String aBreed) {
    super("Dog");
    name = aName;
    breed = aBreed;
    }
    [/code]
    大哥,你在这里面 就把type赋值为"Dog",然后System.out.println(aDog),就会调用toString()方法了

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

报告相同问题?

悬赏问题

  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥20 unity内置语言切换的按钮设置
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?
  • ¥15 html5 qrcode 扫描器
  • ¥15 爬取网页信息并保存需要完整代码