Introduction to Scala Classes and Objects
A class is a blueprint for objects. Once you define a class, you can create objects from the class with the keyword new. A class definition contains field declarations and method definitions from which fields are used to store the state of an object and methods provides the access to fields and alter the state of an object etc.
Want to get certified in Scala! Learn Scala from top Scala experts and excel in your career with Intellipaat’s Scala certification!
e.g.
class Point(i: Int, j: Int) {
var x: Int = i
var y: Int = j
def move(xd: Int, yd: Int) {
x = x + xd
y = y + yd
println ("Point in x location is: " + x);
println ("Point in y location is : " + y);
}
}
Enroll yourself in Online Scala Training and give a head-start to your career in Scala!
Once a class is defined then you should be able to construct an object for this class. The syntax is –
var object-name = new class_name()
e.g.
val pt1 = new Point(10, 0);
Semicolon inference
In scala the use of semicolon at the end of a statement is not compulsory. If you want to write a single statement in a single line then there is no need to use semicolon but the semicolon is required when you want to write many statements on a single line:
Interested in learning Loops? Go through this blog on Loops in R.
e.g.
val s = "hello"; println(s)
if (x < 2)
println("x is less than 2")
else
println("x is not less than 2")
Singleton objects
There is one way in which scala is more object-oriented than Java is that the classes in Scala cannot have a static member. In its place, it has singleton objects. A singleton object definition is like a class definition but in this use the keyword object except for class keyword.
class Point(val i: Int, val j: Int) {
var x: Int = i
var y: Int = j
def moves(xd: Int, yd: Int) {
x = x + xd
y = y + yd
println ("New point in x location is: " + x);
println ("New point in y location is : " + y);
}
}
object Intellipaat {
def main(args: Array[String]) {
val pt1 = new Point(10, 0); // object pt1
pt1.moves(20, 10); // Move the point into another location
}
}
Then Compile and execute the above program as follows:
scalac Intellipaat.scala
scala Intellipaat
Output
New point in x location is: 30
New point in y location is: 10
Interested in learning Scala? Check out the Scala Training in New York!