Objects

  • Objects have State and Behavior
  • State / Variables
    • Objects store their state in variables
    • [Vocab]Often called fields, member variables, or instance variable
  • Behavior / Functions
    • Objects contains functions that can depend on its state
    • [Vocab]When a function is part of an object it’s called a method

Object with State

1
2
3
4
5
6
7
8
9
10
11
object ObjectWithState {

//state of the object
var x: Int = 10
var y: Int = 7

//Behavior of the object
def doubleX(): Unit = {
this.x *= 2
}
}
  • Any variale outside of all methods is part of the state of the object
  • Keyword this stores a reference to the enclosing object
  • Use this. to access state from within the object
  • Declare variables using var if the value can change
  • Declare variables using val to prevent the value from changing
    • Changing a value declared with val will cause an error
  • The variables defining the state of an object have many different names
    • Instance variables
    • Member variables
    • Fields
    • State variables
1
2
3
4
5
6
object ObjectMian {
def main(args: Array[String]): Unit = {
ObjectWithState.doubleX()
println(ObjectWithState.x)
}
}
  • Any code with access to an object can also access it’s state / behavior with the dot notation
  • Can also change the state of an object

Every value in Scala is an object!

Classes

  • Classes are templates for creating objects with similar state and behavior
    • Objects are instantiated from classes using the keyword new
  • Used to create many objects
    • Each object can have a different state
    • Each has its own copies of the state variables
1
2
3
4
5
6
7
8
9
10
11
class Item(val description: String, var price: Double) {
var timesPurchased: Int = 0

def purchase(): Unit = {
this.timePurchased += 1
}

def onSale(): Unit = {
this.price *= 0.8
}
}
  • Define a class to represent an item in a store
  • State and behavior is defined the same way as objects
  • We define one state variable to track the number of times this item was purchased along with a method / behavior to purchase an item
  • We define more behavior to mark an item as on sale by reducing its price by 20%.
  • Classes also contain special methods called constructors
  • This method is called when a new object is created using this class
  • Any code calling the constructor can sue its parameters to set the initial state of the created object
  • [Scala] All constructor parameters become state variables
    • Use var in the constructor id the state variable can change
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
object ItemMain {

def printPrice(item: Item): Unit = {
println("Current price of " + item.description + " is: $" + item.price)
}

def main(args: Array[String]): Unit = {
val cereal: Item = new Item("cereal", 3.0)
val milk: Item = new Item("milk", 2.0)

// Change state using behavior
cereal.purchase()
cereal.onSale()
cereal.purchase()

println(cereal.decription + " has been purchased " + cereal.timePurchaed + " times")
printPrice(cereal)

// Change state directly
milk.price = 1.5

printPrice(milk)
}
}
  • Call a constructor using the new keyword

  • The constructor returns a reference to the created class of the type of the class

  • We have two different object of type item

  • cereal and milk have their own copies of each instance variable

  • Int, Double, Boolean, List, Array, Map

    • Are all classes
    • We use these classes to creat objects
    • var list: List[Int] = List(2, 3, 4)
  • Create objects by calling the constructor for that class

  • List is setup in a way that we don’t use new

  • For our classes we will use the new keyword

Something about homework

  • Method parameters, including constructor, can have default values
    • Any missing arguments are set to the default value
    • Can define a toSting method to print an object with custom formatting
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      class PhysicsVector(var x: Double = 0.0, var y: Double = 0.0, var z: Double = 0.0) {

      override def toString: String = {
      "(" + x + ", " + y + ", " + z + ")"
      }
      }

      val vector: PhysicsVector = new PhysicsVector(4.0, -3.5, 0.7)
      // (4.0, -3.5, 0.7)
      val vector: PhysicsVector = new PhysicsVector(-6.0)
      // (-6.0, 0.0, 0.0)
      val vector: PhysicsVector = new PhysicsVector()
      // (0.0, 0.0, 0.0)

Testing Classes Demo

……
Nothing to show.
……

Lecture Question

Question: In a package named “rhymes” create a Scala class named “Word” with the following:

  • A constructor that takes a value of type List of Strings representing the sounds of the word with each sound as a separate element in the list
    • For more information on sounds, see the Rhyming Dictionary HW handout
  • A method named “alliterationLength” that takes a Word as a parameter and returns an Int. This method returns the number of sounds at the beginning of the 2 words that match
    • Ex. The Lists of sounds
      • List(“K”, “AH0”, “L”, “AE1”, “M”, “AH0”, “T”, “AH0”, “S”) and
      • List(“K”, “AH0”, “L”, “IH1”, “P”, “S”, “OW2”)
      • have an alliteration length of 3 since the first 3 sounds are identical

Testing: In a package named “tests” create a Scala class named “TestWords” as a test suite that tests the functionality listed above