简体   繁体   中英

Java. Abstract elements list. How to determine element type

I have basic abstract class:

 abstract class Graphic 
 {
 abstract void draw(Graphics g);
 }

I have Group class which helps to group elements into particular groups. Notice that this Group class can have other Group elements inside itself.

 class Group extends Graphic
 {
     private ArrayList<Graphic> children = new ArrayList<Graphic>();
 public ArrayList<Graphic> getChildren() 
 {
      return children;
 }

 public void setChildren(ArrayList<Graphic> children) 
 {
          this.children = children;
 }

 public void draw(Graphics g)
 {
     for(Graphic child:children)
     {
          child.draw(g);
     }
 }
 }

Here is the line class which also extends Graphic.

 class Line extends Graphic  {
     private Point startPoint = new Point(0,0);
 private Point endPoint = new Point(1,1);

 public void draw(Graphics g) 
 {
     g.drawLine(startPoint.x, startPoint.y, endPoint.x, cendPoint.y);
 }
 }

I can add Line element or another Group element into Group class children list, that is I can group the groups and these groups can have their own groups too and every group can have line element too, however I'm unable to determine whether the child element is Group or Line. How can I determine whether the element is Group or Line?

instanceof operator or compare object.getClass() object. But checking concrete type of object is not good practice. You should depend only on public interface (your Graphic )

Use instanceof or reflection:

public void draw(Graphics g) 
{
   for(Graphic child:children)
   {
      child.draw(g);

      if (child instanceof Line) {
         System.out.println("child is of type Line");
      }

      System.out.printf("child is of type %s%n", child.getClass());
   }
 }

But you should not need it except for debugging. If you do you better check your design again.

Few more things:

  • Do not use ArrayList except to specify implementation, use List instead (this allows switching implementation say to LinkedList by changing a single line)
  • If Graphics provides no implementation, use interface instead of an abstract class (a class can inherit only one class, but it can implement multiple interfaces)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM