Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

5. Classes and Objects

The examples are stored in project "de.vogella.scala.classexample".

5.1. Overview

A class in Scala is per default defined as public. Everything which is included in the body of the class and which is field or method definition defines the primary constructor of this class.

Here is a very simple class

				
package de.vogella.scala.classexample

class Robot {
	val material = "steel"; 
}

			

5.2. Constructor

The parameter of the primary constructor are directly defined in the class definition. Parameters are directly available within the class. To make them available outside of the class, either define a field and assign the parameter to it, or just add var or val in front of the variable in the primary constructor.

Here is an example for a class with parameters, one of them is automatically available via an accessor.

				
package de.vogella.scala.classexample

class Robot {
	val material = "steel"; 
}

			

				
package de.vogella.scala.classexample

object Test extends Application {
	  val  robot = new RobotWithConstructor (true, "steel")
	  robot.printStatus
	  // material can be accessed as it is defined via val in the primary constructor
	  println (robot.material)
      // Status on cannot be reached, the following line would result in syntax error
      // robot.on
}
			

Auxiliary constructors are defined via the keyword this. They have to call the primary construtor.

				
package de.vogella.scala.classexample

class RobotWithAuxiliaryConstructor  (on: Boolean, val material:String ) {
	 def printStatus() = {
	  println(on)
	  println(material)
    }
  def this() = this(true, "Steel");
}

			

				
package de.vogella.scala.classexample

class TestAuxiliary {
  val  robot = new RobotWithAuxiliaryConstructor()
	  robot.printStatus
	  // material can be accessed as it is defined via val in the primary constructor
	  println (robot.material)
      // Status on cannot be reached, the following line would result in syntax error
      // robot.on
}

			

5.3. Inheritance

A class can inherit from another class via the keyword "extends".

				
package de.vogella.scala.classexample;

class BetterRobot (material:String) extends RobotWithConstructor (true, material ) {
	
}
			

Scala provides a very powerful extention of inheritance, traits. Traits will be covered later.

5.4. Objects

Objects are Singletons. There are for example used to represent an application.

				
package de.vogella.scala.classexample

object Application {
	def main (args: Array[String]) {
	  println("The application is running")
	}
}

			

5.5. Companion Objects

Objects which have the same name as a class and which are defined in the same file are called companion objects. They often provide fabric methods to create an object. See for example the List implementation in Scala.