bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

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.

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);

}

}

Once a class is defined then you should be able to construct 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 single statement in single line then there is no need to use semicolon but semicolon is required when you want write many statements on a single line:

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 a one way in which scala is more object oriented than Java is that the classes in Scala cannot have 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 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

"0 Responses on Scala Classes and Objects"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 04th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Scala Classes and Objects.