这样一个BOX类。它里面可以装水果(fruit),水果分为:苹果apple,橘子orange,梨pear
  有方法add()实现加入一种水果,remove()方法实现撤除一种水果。每种水果都有:种类list,
  重量height,颜色color。
  建立一个可以实现查询水果种类,重量,颜色的BOX。

解决方案 »

  1.   

    在BOX里用一个arraylist把通过add()方法加进来的水果装起来。
      

  2.   

    定义一个interface fruit,这个接口有add,remove方法,接着定义orange,apple,pear实现那个接口.
      

  3.   

    建一个接口A 定义方法getList,getHeight,getColor建立Box
    public class Box
    {
      static HashMap al = new HashMap();
      public void add(String name, A a)
      {
         al.put(name,a);
      }    publci void remove(String name)
      {  
         al.remove(name);
      }   public A getFruit(String name)
      {
         return (A)al.get(name);
      }}
    A 是水果的接口
    所有水果类都必须实现它
      

  4.   

    interface IBox
    {
        List fruits;
        
        public void add(Fruit fruit);
        public Fruit remove(int index);
        public Color queryColor(int index);  
    }interface Constraints
    {
        static final int APPLE = 0;
        static final int PEER = 1;
        static final int ORANGE = 2;
    }/**
     * 水果抽象类,提供水果属性的设置和获取 
     */ 
    abstract class fruit
    {
        private int catagory = -1;
        private double weight;
        private Color _color;
        
        // getter and setter method
        // 水果种类是不可更改的,所以该属性为只读     
        public void setWeight(double weight)
        {
            this.weight = wieght;
        }
        
        public void setColor(Color _color)
        {
            this._color = _color;
        }
        
        public int getCatagory()
        {
            return this.catagory;
        }
        
        public double getWeight()
        {
            return this.weight;
        }
        
        public Color getColor()
        {
            return this._color;
        }
    }class Apple extends fruit
    {
        Apple()
        {
            // 水果属性是一定的,所以在构造中进行属性赋值 
            super.setCatagory(Constraints.APPLE);
        }
        
        public String toString()
        {
            return "这是苹果";
        }
    }class BoxImp implements IBox
    {
        // 实现 add() remove(index)和query(index)方法即可
        public Color queryColor(index) 
        {
            Fruit fruit = fruits.get(index);
            
            return fruit.getColor();
        }
    }
      

  5.   

    谢谢iceandfire(【咖啡沫】) 和w_y_job() 的思维;
     今天好好的研究了一下,感觉有点思路了,非常感谢!
      

  6.   

    interface fruit
    {
       hegiht
       color 
     
       add()
       remove()
    }
    class box implements fruit
    {}
      

  7.   

    此类问题是基本的接口、抽象类的多态问题。现在楼上的已经解决了问题,希望楼主认真学学java,建议看看thinking in java
      

  8.   

    定义一个interface fruit,这个接口有add,remove方法,list,height,color属性,接着定义orange,apple,pear实现那个接口.最后可在Box类中使用了。