vendredi 20 mai 2016

How to interpret and use a class given an interface object?

I have an interface. One of my methods takes as argument an object of this interface. Depending on the concrete class, I want to build a different object.

public interface Shape {
  public void draw();
}

public class Circle implements Shape {
  private int radius;
  //constructor etc.

  public void draw() {
    System.out.println("CIRCLE!");
  }

  public int getRadius() {
    return radius;
  }
}

public class Square implements Shape {
  private int side;

  //constructor etc.

  public void draw() {
    System.out.println("SQUARE!");
  }

  public int getSide() {
    return side;
  }
}


public class MyClass {
  public void myJob(Shape shape) {
    if (shape.getClass().toString().equals("Circle")) {
      // some missing code...what to do here? type cast? transform?
      int radius = shape.getRadius();
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire