java程序问题有些不懂,特别是第3小题。还有就是一会儿output一会儿toString不都是输出吗?求解答!
(1)定义Animal的子类Fish表示鱼,成员变量有生长环境(江,河,湖,海)和游泳速度,成员方法有构造方法和setter,getter方法,并覆盖output()输出所有成员变量。用白鲸豚,2岁,长江,3米/秒创建Fish的对象,并调用toString()。
(2)定义Beast表示兽,成员变量有所在州名,食物,成员方法有构造方法和setter,getter方法,并覆盖toString()输出所有成员变量。用袋鼠,1岁,澳洲,草创建Beast对象,并调用output()。
(3)创建Animal数组保存上述两个对象,然后把数组元素分别强制转换成子类对象后调用子类定义的getter方法。 展开
public class TextAnimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fish fish=new Fish("白鳍豚",2,"长江",3);
System.out.println(fish.toString());
Beast beast=new Beast("袋鼠",1,"澳洲","草");
System.out.println(beast.output());
Anminal anminal[]= {new Anminal(fish.getName(),fish.getAge()),new Anminal(beast.getName(),beast.getAge())};
System.out.println(new Fish(anminal[0].name,anminal[0].age).getName());
System.out.println(new Beast(anminal[1].name,anminal[1].age).getName());
}
}
class Anminal{
String name;
int age;
public Anminal(String name, int age) {
super();
this.name = name;
this.age = age;
}
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 output() {
return "Anminal [name=" + name + ", age=" + age + "]";
}
}
class Fish extends Anminal{
String en;
int v;
Fish(String name, int age) {
super(name, age);
}
Fish(String name, int age, String en, int v) {
super(name, age);
this.en=en;
this.v=v;
}
public String getEn() {
return en;
}
public void setEn(String en) {
this.en = en;
}
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
@Override
public String output() {
return "Fish [en=" + en + ", v=" + v+ "]" ;
}
@Override
public String toString() {
return "Fish [en=" + en + ", v=" + v + ", name=" + name + ", age=" + age + "]";
}
}
class Beast extends Anminal{
String con;
String food;
Beast(String name, int age) {
super(name, age);
}
Beast(String name, int age, String con, String food) {
super(name, age);
this.con=con;
this.food=food;
}
public String getCon() {
return con;
}
public void setCon(String con) {
this.con = con;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
@Override
public String output() {
return "Beast [con=" + con + ", food=" + food + "]";
}
@Override
public String toString() {
return "Beast [con=" + con + ", food=" + food + ", name=" + name + ", age=" + age + "]";
}
}