Inheritance Example


    public class GridObject
    {
        private Grid      theGrid;  // container grid
        private Location  myLoc;    // obj location

        public GridObject(Grid grid, Location loc)
        {
            theGrid = grid;     // init. instance vars.
            myLoc = loc; 
            ⋮
        }

        public Grid grid()
            { return theGrid; }

        public Location location()
            { return myLoc; }

        public String toString()
            { /* returns class name & obj loc */ }

        protected void addToGrid(Grid grid, Location loc)
            { … }

        protected void removeFromGrid()
            { … }

        protected void changeLocation(Location newLoc)
            { … }

        public void act()
            { /* does nothing */ }
    }
    public class ColorBlock extends GridObject
    {
        // (inherits grid and location)
        private Color    theColor;      // block color

        public ColorBlock(Color colorValue,
                          Grid grid, Location loc)
        {
            super(grid, loc);       // call superclass constructor
            theColor = colorValue;  // init. new instance var.
        }

        public Color color()
            { return theColor; }

        public String toString()
            {   return theColor.toString() + " "
                        + location().toString(); }
    }
ColorBlock instance variables:
  • grid, location, color
ColorBlock methods:
  • grid(), location(), color()
  • toString() (redefined method overrides inherited method)
  • addToGrid, removeFromGrid, changeLocation
  • act()

Alyce Brady, Kalamazoo College