public abstract class animal {
protected String name;
public animal(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void show();
}
---------------------------------2
public interface lu {
public int leg();
}
-------------------------3
public class cat extends animal implements lu{
private int leg;
public cat(String name, int leg) {
super(name);
this.leg = leg;
}
public int getLeg() {
return leg;
}
public void setLeg(int leg) {
this.leg = leg;
}
---------------------------------------------4
public class duck extends animal implements lu {
private int leg;
public duck(String name, int leg) {
super(name);
this.leg = leg;
}
public int getLeg() {
return leg;
}
public void setLeg(int leg) {
this.leg = leg;
}
@Override
public void show() {
// TODO Auto-generated method stub
System.out.println("嘎");
}
@Override
public int leg() {
return this.leg;
}
}
------------------5
public class hai extends animal {
public hai(String name) {
super(name);
}
@Override
public void show() {
System.out.println("海豚");
}
}
---------------
public class test {
private static Object lu;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
animal[] a=new animal[3];
a[0]=new cat("小猫",4);
a[1]=new duck("鸭子",2);
a[2]=new hai("海豚");
System.out.println("动物的名字"+"\t"+"腿数"+"\t\t"+"动物叫");
for(int i=0;i<a.length;i++)
{
if(a[i] instanceof lu)
{
String name=a[i].getName();
int legnum=((lu)a[i]).leg();
//System.out.println(name+ "\t\t" +legnum+ "\t\t");
System.out.print(name + "\t\t" + legnum + "\t\t");
a[i].show();
}
else
{
String name=a[i].getName();
System.out.print(name+ "\t\t" +0+ "\t\t");
a[i].show();
}
}
}
}