日期:2014-05-20  浏览次数:20657 次

各位大哥,小女有一关于父类的引用指向子类的对象的问题想请教大家
这个程序不知道哪里错了,可能是   public   void   f(Animal   a)   错了

class   Animal{
private   String   name;
public   Animal(String   name){
this.name   =   name;
}
public   String   getName()   {
return   name;
}
public   void   setName(String   name)   {
this.name   =   name;
}
}

class   Dog   extends   Animal{
private   String   furColor;
public   Dog(String   n,   String   c){
super(n);
furColor   =   c;
}

public   String   getFurcolor()   {
return   furColor;
}
public   void   setFurcolor(String   furcolor)   {
this.furColor   =   furcolor;
}
}

class   Cat   extends   Animal{
        private   String   eyescolor;
        public   Cat(String   n,String   e)   {
super(n);
eyescolor   =   e;
}
public   String   getEyescolor()   {
return   eyescolor;
}
public   void   setEyescolor(String   eyescolor)   {
this.eyescolor   =   eyescolor;
}


}

public   class   Test   {

public   static   void   main(String[]   args)   {
Test   test   =   new   Test();
Animal   a   =   new   Animal( "name ");
Cat   c   =   new   Cat( "catname ", "blue ");
Dog   d   =   new   Dog( "dogname ", "black ");
test.f(a);  
test.f(c);
test.f(d);

          public   void   f(Animal   a){                           //这里可能错了,但不知道怎么错了
                  System.out.println( "name: "+a.getName());
                  if(a   instanceof   Cat){
                  Cat   cat   =   (Cat)a;    
                  System.out.println( "   "+cat.getEyescolor()+ "eyes ");
                  }
                  else   if(a   instanceof   Dog){
                  Dog   dog   =   (Dog)a;  
                  System.out.println( "   "+dog.getFurcolor()+ "   fur ");
                  }
                 
                }

还有什么叫父类的引用指向子类的对象   ,体现在这个程序中有什么呢好处   ?拜托各位大哥

------解决方案--------------------
public class Test {

public static void main(String[] args) {
Test test = new Test();
Animal a = new Animal( "name ");
Cat c = new Cat( "catname ", "blue ");
Dog d = new Dog( "dogname ", "black ");