Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 10:48:06 Viewed : 227
Scala object and class
class MyClassName{
}
var s = new MyClassName () // Creating an object
· Define a Scala class constructor
class Employee(var firstName: String, var lastName: String) {
def printFullName() =
println(s"$firstName $lastName")
}
Notice that there’s no need to create “get” and “set” methods to access the fields in the class.
Example:
Following example illustrates about Scala object and class
Save the file as − Employee.scala.
package runnerdev
class Employee {
var id: Int = 11 // All fields must
be initialized
var name: String = "Ram"
}
object ClassAndObject {
def main(args: Array[String]) {
var s = new Employee() // Creating an
object
println(s.id + " " + s.name)
}
}
compile
and run the above example as follows
scala> scalac Employee.scala
scala> scala Employee
OutPut:
11 Ram
Example:
Following example illustrates about Scala class constructor
class Point(var x: Int, var y: Int) {
def move(dx: Int, dy: Int): Unit = {
x = x + dx
y = y + dy
}
s"($x, $y)"
}
val point1 = new Point(2, 3)
println(point1.x) // 2
println(point1) // prints (2, 3)