要求是:编写一个可吃接口Eatable,其中有一个haoToEat抽象方法。创建两组类Animal类和Fruit类,每种可吃的类必须能实现Eatable接口。并创建Animal类的子类Tiger、Chicken和Elephant,创建Fruit类的子类Apple和Orange。在每一个类中重写toString方法。创建测试程序。
在测试程序中可以调用showObject方法显示对象:
public static void showObject(Object o)
{System.out.println(o);
if(o instanceof Eatable)
{
((Eatable)o).howToEat();
}
}
不太懂showObject
下面是我自己写的一段程序
interface Eatable
{
public void HowToEat();
}
class Animal
{
String Type;
int legs;
String HairColor;
Animal(String t,int l,String h)
{
Type=t;
legs=l;
HairColor=h;
}
}
class Tiger extends Animal
{
String Series;
Tiger(String t, int l, String h,String s) {
super(t, l, h);
Series=s;
}
public String tostring(){
System.out.println("老虎的基本情况:");
return "[老虎的种类:"+Type+",这只老虎的类型:"+Series+",腿的数量:"+legs+"个,老虎的毛色:"+HairColor+",]";
}
}
class Chicken extends Animal implements Eatable
{
int Wing;
Chicken(String t, int l, String h,int w) {
super(t, l, h);
Wing=w;
}
public String tostring(){
System.out.println("鸡的基本情况:");
return "[鸡的种类:"+Type+",这只鸡翅膀的个数:"+Wing+",腿的数量:"+legs+"个,鸡的毛色:"+HairColor+",]";
}
public void HowToEat() {
System.out.println("烤鸡。");
}
}
class Elephant extends Animal
{
String NoseCanDrink;
Elephant(String t, int l, String h,String n) {
super(t, l, h);
NoseCanDrink=n;
}
public String tostring(){
System.out.println("大象的基本情况:");
return "[大象的种类:"+Type+",大象的"+NoseCanDrink+",腿的数量:"+legs+"个,大象的毛色:"+HairColor+",]";
}
}
class Fruit implements Eatable
{
String PeelColor;
int LeavesNumber;
String Origin;
Fruit(String p,int l,String o)
{
PeelColor=p;
LeavesNumber=l;
Origin=o;
}
public void HowToEat()
{
System.out.println("咬着吃。");
};
}
class Apple extends Fruit implements Eatable
{
String Shape;
Apple(String p, int l,String o,String s) {
super(p, l,o);
Shape=s;
}
public String tostring(){
System.out.println("苹果的基本情况:");
return "[苹果的原产地:"+Origin+",苹果的外形:"+Shape+",每个苹果叶子的数量"+LeavesNumber+"个,苹果果皮的颜色:"+PeelColor+",]";
}
public void HowToEat() {
System.out.println("苹果的吃法:榨汁(苹果汁),煎炸(苹果派),晾干(苹果干),做果酱,生吃,拌水果沙拉。");
}
}
class Orange extends Fruit implements Eatable
{
String Pulp;
Orange(String p, int l, String o,String u) {
super(p, l, o);
Pulp=u;
}
public String tostring(){
System.out.println("橙子的基本情况:");
return "[橙子的原产地:"+Origin+",橙子果肉的形状:"+Pulp+",每个橙子叶子的数量"+LeavesNumber+"个,橙子果皮的颜色:"+PeelColor+",]";
}
public void HowToEat()
{
System.out.println("橙子的吃法:直接吃、榨橙汁、做菜(香橙排骨等)、炖冰糖、炖盐巴(炖法:把橙子顶部切开露出部份橙肉即可,放上冰糖或盐巴,再盖回顶部。)");
}
}
public class HowToEatDemo1 {
public static void main(String[] args){
Animal t=new Tiger("哺乳动物",4,"黄色","东北虎");
Animal c=new Chicken("鸟类",2,"淡黄色",2);
Animal e=new Elephant("哺乳动物",4,"灰色","用鼻子喝水");
Fruit a=new Apple("红色",2,"北方","椭圆形");
Fruit o=new Orange("橙色",2,"南方","瓣状");
showObject(t);
showObject(c);
showObject(e);
showObject(a);
showObject(o);
}
public static void showObject(Object object) {
System.out.println(object);
if (object instanceof Eatable) {
((Eatable) object).HowToEat();
}
}
}
可是 tostring 显示不出来,是怎么回事?