The Artima Developer Community
Sponsored Link

Java Answers Forum
Interface Question

9 replies on 1 page. Most recent reply: Apr 13, 2002 9:50 AM by Jay Kandy

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 9 replies on 1 page
Patti

Posts: 46
Nickname: patti
Registered: Feb, 2002

Interface Question Posted: Apr 11, 2002 11:21 AM
Reply to this message Reply
Advertisement
I'm supposed to modify a program that currently uses an array of Shapes (made by shape creator) to: an array of objects using an interface. Question is: What objects can be assigned to an array referencing an interface? I'm unclear on this. Please help.


Jay Kandy

Posts: 77
Nickname: jay
Registered: Mar, 2002

Re: Interface Question Posted: Apr 11, 2002 5:23 PM
Reply to this message Reply
> an interface? I'm unclear on this. Please help.
We have some thing in common. I am unclear too :)
From the little I understand, you could try using instanceof operator.
for()
{
if( array[i] instanceof Interface )
// ...
}

Patti

Posts: 46
Nickname: patti
Registered: Feb, 2002

Re: Interface Question Posted: Apr 11, 2002 6:10 PM
Reply to this message Reply
Well, the program has so many parts I was trying to avoid printing it. Here is the main part. There are Circle, Shape, Rectangle, Oval, Square, Polygon, Line, Shape classes I didn't include here.
I'm supposed to change the array of shapes to a Drawable objects array based on Interface Drawable. I am then supposed to describe "what kind of objects" I can use ??? I don't understand what the teacher is asking me to do here. Is she asking me to get rid of all the shapes or what?

import java.applet.*;
import java.awt.*;
import java.util.Random;
 
//==================================================================
//  This applet creates and draws multiple random shapes.
//==================================================================
 
public class Random_Draw extends Applet {
 
   final int MAX_SHAPE = 50;
 
   Shape[] shapes = new Shape[MAX_SHAPE];
   Shape_Creator creator;
 
   //------------------------------------------------------
   //  Creates and stores multiple shapes.
   //------------------------------------------------------
 
   public void init() {
 
      shapes = new Shape[MAX_SHAPE];
      creator = new Shape_Creator();
 
      for (int index = 0; index < MAX_SHAPE; index++) {
 
         shapes[index] = creator.new_shape();
      }
 
   }  // method init
 
 
   //------------------------------------------------------
   //  Draws all of the shapes on the applet.
   //------------------------------------------------------
 
   public void paint (Graphics page) {
   	
   	for (int index = 0; index < MAX_SHAPE; index++){
   		
   		shapes[index].draw(page);
     }
     
   }  // method paint
 
}  // class Random_Draw
 
//==================================================================
//  The Shape_Creator class contains code to create randome shapes,
//  each with random size, color, and location.
//==================================================================
 
class Shape_Creator {
 
   final int COLOR_MAX = 255;
   final int DIMENSION_MAX = 400;
   final int NUM_SHAPES = 6;
   final int POLY_MAX = 9;
 
   final int LINE = 1;
   final int RECTANGLE = 2;
   final int OVAL = 3;
   final int SQUARE = 4;
   final int CIRCLE = 5;
   final int POLYGON = 6;
 
 
 
   Random rand = new Random();
 
   //------------------------------------------------------
   //  Returns a random integer between 1 and max.
   //------------------------------------------------------
 
   public int random_int (int max) {
 
      return Math.abs(rand.nextInt()) % max + 1;
 
   }  // method random_int
 
   //------------------------------------------------------
   //  Returns a random color created using random RGB
   //  values.
   //------------------------------------------------------
 
   public Color random_color() {
 
 
      return new Color (random_int (COLOR_MAX), 
                        random_int (COLOR_MAX), 
                        random_int (COLOR_MAX));
 
 
   }  // method random_color
 
 
   //------------------------------------------------------
   //  Returns a random shape with random characteristics.
   //------------------------------------------------------
 
   public Shape new_shape() {
 
 
      Shape result;
 
      int x1, y1, x2, y2, x, y, width, height,length;
      int[] xPolygon = new int [POLY_MAX];
      int[] yPolygon = new int [POLY_MAX];
 
 
      switch (random_int(NUM_SHAPES)) {
 
          case LINE:
            x1 = random_int (DIMENSION_MAX);
            y1 = random_int (DIMENSION_MAX);
            x2 = random_int (DIMENSION_MAX);
            y2 = random_int (DIMENSION_MAX);
            result = new Line (random_color(),x1,y1,x2,y2);
            break;
 
           case OVAL:
            x = random_int (DIMENSION_MAX);
            y = random_int (DIMENSION_MAX);
            width = random_int (DIMENSION_MAX);
            height = random_int (DIMENSION_MAX);
            result = new Oval (random_color(),x,y,width,height);
            break;
            
           case SQUARE:
            x = random_int (DIMENSION_MAX);
            y = random_int (DIMENSION_MAX);
            width = random_int (DIMENSION_MAX);
            height = width;
            result = new Rectangle (random_color(),x,y,width,height);
            break; 
            
           case CIRCLE:
            x = random_int (DIMENSION_MAX);
            y = random_int (DIMENSION_MAX);
            width = random_int (DIMENSION_MAX);
            height = width;
            result = new Oval (random_color(),x,y,width,height);
            break; 
 
           case POLYGON:
            length = random_int (POLY_MAX);
            for (int i = 0; i < length; i++){
            xPolygon[i] = random_int (DIMENSION_MAX);
            yPolygon[i] = random_int (DIMENSION_MAX);
             }           
           
            result = new Polygon (random_color(),xPolygon,yPolygon, length);           
            break; 
 
           case RECTANGLE:
           default:
            x = random_int (DIMENSION_MAX);
            y = random_int (DIMENSION_MAX);
            width = random_int (DIMENSION_MAX);
            height = random_int (DIMENSION_MAX);
            result = new Rectangle (random_color(), x, y, width, height);
            break;
      }
      return result;
 
   }  // method new_shape
}  // class Shape_Creator
 


Here's Drawable:

public interface Drawable {

public void draw ();


}//class drawable

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Interface Question Posted: Apr 11, 2002 6:12 PM
Reply to this message Reply
No, the idea of using an inteface is to divorce yourself from the knowledge of the exact object type. Using interfaces will make your code much more flexible. instanceof will have the opposite effect and should be used more sparingly.

Patti, I think we need a little more detail about the existing interfaces and classes you are using, but based on what you said, it looks like you are are the right track already. You said had an array of Shapes; if you are referring to java.awt.Shape, then you have already have a collection based on an interface, because java.awt.Shape is an interface. If you have a collection of these, then the objects in this collection could be Rectangles, Areas, Polygons, or intances of any other class that implements Shape. Of course, if you had a collection of some specific object, like Rectangle, it could only contain Rectagles (and its subclasses).

It kind of sounds like you are a point in your class where you have covered arrays and are about to delve into Collections, so the instructor wants to introduce the concept of using an array of Object, or an array of a particular interface.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Interface Question Posted: Apr 11, 2002 6:13 PM
Reply to this message Reply
Oops -- your last reply appeared while I was typing, so disregard my request for more specific details about your assignment!

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Interface Question Posted: Apr 11, 2002 6:20 PM
Reply to this message Reply
Ah, looking at your code, I understand what your instructor seeks: Using an interface will eliminate the need for the switch. If all the object implement a Drawable interface, then you don't need to know which object you are drawing, it will draw itself. I have to run right now, but if you need more specifics and you haven't gotten any by tonight from someone else, I'll elaborate then.

Patti

Posts: 46
Nickname: patti
Registered: Feb, 2002

Re: Interface Question Posted: Apr 11, 2002 6:36 PM
Reply to this message Reply
Thank you Matt. You're always helpful !!!

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Interface Question Posted: Apr 12, 2002 12:23 AM
Reply to this message Reply
Okay, I think this is along the lines of what you are after. I have only implemented a DrawableRectangle and left all the other shapes for you, but I think you'll get the picture. The idea is that you have a collection of Drawables, not Shapes, so you can iterate through it and ask each one to draw itself (since they all must implement draw()).

Some notes:
- I changed the creator class name to reflect the fact that it is creating Drawables.
- I've commented out all the cases in your switch except the rectangle case in the creator method -- you can uncomment the others as you create their Drawable counterparts.
- For ease of posting, I've not made the interface public and put everything in one file, but in real work, you would want each interface and class in its own file (and probably in a package).
- I made the DrawableRectangle extend Rectangle, which I think is okay in this simple case, but some people always prefer composition. Using composition, the DrawableRectangle class would contain a Rectangle instance variable along with the Color it has already. If you used composition, you'd probably use a different name, like ColorfulRectangleDrawer, to reflect the fact that it is an object which draws colorful rectangles (and to confuse people who are looking for handy furniture objects!).
- I added a main(), so that you can run it stand-alone (I find this makes for quicker test runs).

import java.applet.*;
import java.awt.*;
import java.util.Random;
 
//=================================================================
//                         Drawable
//=================================================================
interface Drawable extends Shape
{
    public void draw( Graphics page );
}
 
//=================================================================
//                       DrawableRectangle
//=================================================================
class DrawableRectangle extends Rectangle implements Drawable
{
    Color color;
 
    DrawableRectangle( Color c, int x, int y, int width, int height )
    {
        super( x, y, width, height );
        color = c;
    }
 
    public void draw( Graphics page )
    {
        Color prevColor = page.getColor();
        page.setColor(color);
        page.drawRect( x, y, width, height);
        page.setColor(prevColor);
    }    
}
 
//=================================================================
//  This applet creates and draws multiple random shapes.
//=================================================================
public class Random_Draw extends Applet
{
    final int MAX_SHAPE = 50;
    Drawable[] shapes = new Drawable[ MAX_SHAPE ];
    Drawable_Creator creator;
 
    public static void main(String[] args)
    {
        Applet applet = new Random_Draw();
        javax.swing.JFrame frame = new javax.swing.JFrame("Random Shapes");
        frame.setSize(800, 800);
        frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(applet);
        applet.init();
        applet.start();
        frame.setVisible(true);
    }
    //-----------------------------------------------------
    //  Creates and stores multiple shapes.
    //-----------------------------------------------------
    public void init()
    {
        shapes = new Drawable[ MAX_SHAPE ];
        creator = new Drawable_Creator();
        for(int index = 0;index < MAX_SHAPE;index++)
            shapes[ index ] = creator.new_shape();
    } // method init
    //-----------------------------------------------------
    //  Draws all of the shapes on the applet.
    //-----------------------------------------------------
    public void paint(Graphics page)
    {
        for(int index = 0;index < MAX_SHAPE;index++)
            shapes[ index ].draw(page);
    } // method paint
} // class Random_Draw
 
//====================================================
//  The Shape_Creator class contains code to create random shapes,
//  each with random size, color, and location.
//====================================================
class Drawable_Creator
{
    final int COLOR_MAX = 255;
    final int DIMENSION_MAX = 400;
    final int NUM_SHAPES = 6;
    final int POLY_MAX = 9;
    final int LINE = 1;
    final int RECTANGLE = 2;
    final int OVAL = 3;
    final int SQUARE = 4;
    final int CIRCLE = 5;
    final int POLYGON = 6;
    Random rand = new Random();
 
    //-----------------------------------------------------
    //  Returns a random integer between 1 and max.
    //-----------------------------------------------------
    public int random_int(int max)
    {
        return Math.abs(rand.nextInt()) % max + 1;
    } // method random_int
    
    //-----------------------------------------------------
    //  Returns a random color created using random RGB
    //  values.
    //-----------------------------------------------------
    public Color random_color()
    {
        return new Color(random_int(COLOR_MAX), random_int(COLOR_MAX), random_int(COLOR_MAX));
    } // method random_color
    
    //-----------------------------------------------------
    //  Returns a random shape with random characteristics.
    //-----------------------------------------------------
    public Drawable new_shape()
    {
        Drawable result;
        int x1, y1, x2, y2, x, y, width, idth, height, length;
        int[] xPolygon = new int[ POLY_MAX ];
        int[] yPolygon = new int[ POLY_MAX ];
 
        switch(random_int(NUM_SHAPES))
        {
/***************
   To do: Create the Drawable version of all these classes, then uncomment
          this code!

          case LINE:
              x1 = random_int(DIMENSION_MAX);
              y1 = random_int(DIMENSION_MAX);
              x2 = random_int(DIMENSION_MAX);
              y2 = random_int(DIMENSION_MAX);
              result = new Line(random_color(), x1, y1, x2, y2);
              break;
          
          case OVAL:
              x = random_int(DIMENSION_MAX);
              y = random_int(DIMENSION_MAX);
              width = random_int(DIMENSION_MAX);
              height = random_int(DIMENSION_MAX);
              result = new Oval(random_color(), x, y, width, height);
              break;
          
          case SQUARE:
              x = random_int(DIMENSION_MAX);
              y = random_int(DIMENSION_MAX);
              width = random_int(DIMENSION_MAX);
              height = width;
              result = new Rectangle(random_color(), x, y, width, height);
              break;
          
          case CIRCLE:
              x = random_int(DIMENSION_MAX);
              y = random_int(DIMENSION_MAX);
              width = random_int(DIMENSION_MAX);
              height = width;
              result = new Oval(random_color(), x, y, width, height);
              break;
          
          case POLYGON:
              length = random_int(POLY_MAX);
              for(int i = 0;i < length;i++)
              {
                  xPolygon[ i ] = random_int(DIMENSION_MAX);
                  yPolygon[ i ] = random_int(DIMENSION_MAX);
              }
              result = new Polygon(random_color(), xPolygon, yPolygon, length);
              break;
***************/
 
          case RECTANGLE:
          default:
              x = random_int(DIMENSION_MAX);
              y = random_int(DIMENSION_MAX);
              width = random_int(DIMENSION_MAX);
              height = random_int(DIMENSION_MAX);
              result = new DrawableRectangle(random_color(), x, y, width, height);
              break;
        }
        return result;
    } // method new_shape
} // class Shape_Creator

Patti

Posts: 46
Nickname: patti
Registered: Feb, 2002

Re: Interface Question Posted: Apr 12, 2002 7:46 AM
Reply to this message Reply
I got it! Thanks so much.

Jay Kandy

Posts: 77
Nickname: jay
Registered: Mar, 2002

Re: Interface Question Posted: Apr 13, 2002 9:50 AM
Reply to this message Reply
I thought you were copying array of Shapes to arrays of concrete classes. Anyways you got that solved.

Flat View: This topic has 9 replies on 1 page
Topic: How to count total rown using jdbc Previous Topic   Next Topic Topic: Question about ChatServer and ChatClient! Please help! Urgent

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use