More OOP

Question Click to View Answer

What does the following code print?

abstract class Mammal {
  val warmBlooded: Boolean = true
}

class Pig extends Mammal

var missPiggy = new Pig

println(missPiggy.warmBlooded)

true is printed.

Mammal is an abstract class that cannot be instantiated directly, but can be used as a base class for inheritance. The Pig class inherits from the Mammal class and the new keyword is used to create an instance of the Pig class.

What does the following code print?

abstract class Plane {
  val fun: String = {
    "You bet"
  }
}

var bomber = new Plane
println(bomber.fun)

This code throws an error.

Plane is defined an an abstract class and cannot be instantiated directly. Plane can be subclassed and the subclass can be instantiated.

What does the following code print?

class Whatever {
  def aaa(s: String): String = {
    "I like words"
  }
  def aaa(i: Int): String = {
    "Numbers are fun"
  }
}

var w = new Whatever
println(w.aaa("hi"))
println(w.aaa(34))

w.aaa("hi") returns "I like words".

w.aaa(34) returns "Numbers are fun".

The Whatever class is using a technique called method overloading with the aaa method.

aaa is referred to as an overloaded method.

When the aaa method is called with a string argument, the aaa(s: String) method is invoked.

When aaa is called with an integer argument, the aaa(i: Int) method is invoked.

What does the following code print?

class Cloud {
  def apply() = {
    "floating"
  }
}

var c = new Cloud
println(c.apply())

floating is printed.

The apply method is special and is called by default if the method name is not specified. c() also returns "floating" because the apply method is automatically used if no method name is specified. The apply method is the only method with this special behavior.

What does the following code print?

class Star {
  def apply() = {
    "shining"
  }
}

var s = new Star
println(s())

shining is printed.

The apply method is special and is called by default if the method name is not specified. s.apply() also returns "shining", but the apply method will be called by default if no method name is specified as well.