在农场系统例子中,如何调用Apple,Grape类中的SET/GET方法?是不是作者错了?
Apple和Grape类实现了Fruit接口,按照作者的意思,应该如下调用:
public class a 
{
    public static void main(String[] args) 
    {
        FruitGardener a=new AppleGardener();
        a.factory().“这里如何调用SET/GET方法?返回的是Fruit类型呀,难道要强制转换?”;
    }
}

解决方案 »

  1.   

    public interface FruitGardener
    {
        public Fruit factory();
    }public interface Fruit
    {
        void grow();    void harvest();    void plant();
    }public class AppleGardener implements FruitGardener 
    {
        public Fruit factory()
        {
            return new Apple();
        }
    }public class Apple implements Fruit
    {
        private int treeAge;    public void grow()
        {
         System.out.println("Apple is growing...");
        }    public void harvest()
        {
         System.out.println("Apple has been harvested.");
        }    public void plant()
        {
            System.out.println("Apple has been planted.");
        }    public int getTreeAge()
        {
            return treeAge;
        }    public void setTreeAge(int treeAge)
        {
            this.treeAge = treeAge;
        }}
      

  2.   

    hellwindy(夜神·月),你的意思是真的要强制转换?不是我理解错了?
      

  3.   

    FruitGardener a=new AppleGardener()
    a.factory()new AppleGardener()返回一個AppleGardener類型的對象,賦值給FruitGardener(傳第的是一個 引用),這裡是"上傳".
    對象類型自動變化成基類的類型,但此時在a的實際對象是個AppleGardener
    類型的.a.factory(),調用的是AppleGardener類的方法,返回值為Apple類型的對象.
      

  4.   

    不可能,返回的要是Apple对象,怎么没有SET/GET方法?