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

调用基类的构造函数

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()方法了

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • iteye_14351 2010-06-29 16:01

    public Animal(String aType) {
    type = [b]new String(aType)[/b];
    }
    在这地方调用了,你自己写的string函数。

    评论
    解决 无用
    打赏 举报
  • nmemory 2010-06-29 16:34

    JAVA中有个规则是,当你打印一个对象时候,就调用这个对象的toString()方法,toString()是最根部的Object类的方法,这里被你重写了。

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题