{ |one, step, back| }

The Shape Example in Scala

Contributed by Giordano Scalzo

Code for Scala

File: Polymorph.scala

package polymorph

abstract class Shape(initx:Int, inity:Int){
  var x: Int = initx
  var y: Int = inity

  def moveTo(newx: Int, newy: Int){
    x = newx
    y = newy
  }
  def rMoveTo(dx: Int, dy: Int){
    moveTo(x + dx, y+ dy)
  }
  def draw() = {}
}

class Rectangle(initx: Int, inity: Int, initwidth: Int, initheight: Int) extends Shape(initx, inity){
  var width = initwidth
  var height = initheight
  override def draw() = println("Drawing a Rectangle at:(" + x + "," + y + 
                                    "), width " + width + ", height " + height)
}

class Circle(initx: Int, inity: Int, initradius: Int) extends Shape(initx, inity){
  var radius = initradius
  override def draw() = println("Drawing a Circle at:(" + x + "," + y + 
                                    "), radius " + radius)
}

object Polymorph {
  def main(args : Array[String]) : Unit = {
    // create a collection containing various shape instances
    val shapes = new Rectangle(10, 20, 5, 6) :: new Circle(15, 25, 8):: Nil
    shapes.foreach(ashape =>{ 
      ashape.draw()
      ashape.rMoveTo(100,100)      
      ashape.draw()
      }
    )
    
    // access a rectangle specific function
	val rectangle = new Rectangle(0, 0, 15, 15)
	rectangle.width_=(30)
	rectangle.draw()
  }
}

Output

Drawing a Rectangle at:(10,20), width 5, height 6
Drawing a Rectangle at:(110,120), width 5, height 6
Drawing a Circle at:(15,25), radius 8
Drawing a Circle at:(115,125), radius 8
Drawing a Rectangle at:(0,0), width 30, height 15