Week 2 Code Snippets

Java Classes

public class MyClass {
  // private immutable fields
  private final int x;
  private final int y;
  // private mutable fields
  private int z;

  // constructor
  public MyClass(int x, int y, int z) {
    this.x = x;
    this.y = y;
    this.z = z;
    System.out.println("Constructor of MyClass called");
  }

  // alternative constructor with default values
  public MyClass(int x, int y) {
    this(x, y, 0);
  }

  // getters and setters
  public int getY() {
    return y;
  }

  public int getZ() {
    return z;
  }

  public void setZ(int z) {
    this.z = z;
  }

  public int doubleX() {
    return 2 * x;
  }

  // a static method is statically linked to the class name, rather than related to an object
  public static void main(String[] args) {
    MyClass o = new MyClass(1,2,3);
  }
}

C++ Classes

class MyClass {
  private:
    // private immutable fields
    int const x;
    int const y;
    // private mutable field
    int z;

  public:
    // constructor
    MyClass(int x, int y, int z) : x(x), y(y), z(z) {}
    MyClass(int x, int y) : MyClass(x,y,0) {}

    // getters and setters
    int getY() const {
      return y;
    }

    int getZ() const {
      return z;
    }

    void setZ(int z) {
      this->z = z;
    }

    int doubleX() {
      return 2*x;
    }
};

// a global main function
int main(int argc, char* argv[]) {
  MyClass *o = new MyClass(1,2,3);

  delete o;
  return 0;
}

Scala Classes

class MyClass(x: Int, val y: Int, var z: Int):
  // private mutable field, cannot be set from "constructor"
  private var x2: Int = x
  // Scala does not offer constructors; instead, constructor code is simply listed in the class body
  println("Constructor of MyClass called")

  // a private immutable field with a compound initializer expression
  private val x3: Int = {
    println("Initializing x3")
    x + 1
  }

  // a public immutable field with a compound (long-running) initializer expression
  val x4 = {
    Thread.sleep(5000)
    5
  }

  // a parameterless method with a long-running body,
  // executed each time we invoke x5
  def x5 = {
    Thread.sleep(5000)
    5
  }

  // a memoized def with a long-running initializer body,
  // executed once on first access of x6
  lazy val x6 = {
    Thread.sleep(5000)  
    5
  }

  // Scala method
  def doubleX() : Int = 2 * x

  println("Another part of the constructor")

  // apply methods can be invoked without explicitly naming
  // the method name
  def apply(i: Int) : Int =
    i + y + z
  end apply

end MyClass

// A companion object. Can be used to offer additional factory methods
object MyClass:
  def apply(x: Int, y: Int) : MyClass =
    new MyClass(x, y, 0)
  end apply
end MyClass

// No static methods, program entry point is an ordinary method in some object
object Main:
  def main(args: Array[String]) =
    val o = new MyClass(1,2,3)
  end main
end Main