Advertisement
Guest User

Untitled

a guest
Aug 6th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.02 KB | None | 0 0
  1. package tests
  2.  
  3. object MultipleConstructors {
  4.    
  5.   def main(args: Array[String]) {
  6.  
  7.     // (1) use the primary constructor
  8.     val al = new Person("Alvin", "Alexander", 20)
  9.     println(al)
  10.  
  11.     // (2) use a secondary constructor
  12.     val fred = new Person("Fred", "Flinstone")
  13.     println(fred)
  14.  
  15.     // (3) use a secondary constructor
  16.     val barney = new Person("Barney")
  17.     println(barney)
  18.  
  19.   }
  20.  
  21. }
  22.  
  23. /**
  24.  * The main/primary constructor is defined when you define your class.
  25.  */
  26. class Person(val firstName: String, val lastName: String, val age: Int) {
  27.    
  28.   /**
  29.    * A secondary constructor.
  30.    */
  31.   def this(firstName: String) {
  32.     this(firstName, "", 0);
  33.     println("\nNo last name or age given.")
  34.   }
  35.    
  36.   /**
  37.    * Another secondary constructor.
  38.    */
  39.   def this(firstName: String, lastName: String) {
  40.     this(firstName, lastName, 0);
  41.     println("\nNo age given.")
  42.   }
  43.    
  44.   override def toString: String = {
  45.     return "%s %s, age %d".format(firstName, lastName, age)
  46.   }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement