父类应用指向子类对象,我这种写不知道哪里错了,请帮我看看
小弟初接触Java,请各位高手帮我修改下,
class Animals{ private String color; private int high; Animals(){ } Animals(String color,int high){ this.color = color; this.high = high; } public void info(Animals a){ System.out.println("color="+a.color); if (a instanceof Bird) { Bird bird = (Bird) a; System.out.println("name="+bird.name+" high="+bird.high); } else System.out.println("I'd not konw who is this"); }}class Bird extends Animals{ private String name; Bird(){ } Bird(String name,String color,int high){ super(color,high); this.name = name; } }public class FatherSub{ public static void main(String arg[]){ Animals a = new Animals(); Bird b = new Bird("john","blue",12); a.info(b);}}package test;class Animals{ private String color; private int high; Animals(){} Animals(String color,int high){ this.color = color; this.setHigh(high); } public void info(Animals a){ System.out.println("color="+a.color); if (a instanceof Bird){ Bird bird = (Bird) a; System.out.println("name="+bird.getName()+" high="+bird.getHigh()); }else System.out.println("I'd not konw who is this"); } public void setHigh(int high) { this.high = high; } public int getHigh() { return high; }}class Bird extends Animals{ private String name; Bird(){} Bird(String name,String color,int high){ super(color,high); this.setName(name); } public void setName(String name) { this.name = name; } public String getName() { return name; } }public class FatherSub{ public static void main(String arg[]){ Animals a = new Animals(); Bird b = new Bird("john","blue",12); a.info(b); }}
[解决办法]
class Animals {
private String color;
protected int high;
Animals() {
}
Animals(String color, int high) {
this.color = color;
this.high = high;
}
public void info(Animals a) {
System.out.println("color=" + a.color);
if (a instanceof Bird) {
Bird bird = (Bird) a;
System.out.println("name=" + bird.name + " high=" + bird.high);
} else
System.out.println("I'd not konw who is this");
}
}
class Bird extends Animals {
String name;
Bird() {
}
Bird(String name, String color, int high) {
super(color, high);
this.name = name;
}
}
public class FatherSub {
public static void main(String arg[]) {
Animals a = new Animals();
Bird b = new Bird("john", "blue", 12);
a.info(b);
}
}