Scala is a functional as well as an object-oriented programming language. The Object-oriented programming language is based on the concept of "objects". An Object is a placeholder to store data in the form of fields. Let us see the Scala OOP concept in the following section.

Scala Classes

Classes in Scala are blueprints for creating objects. They can contain methods, values, variables, types, objects, traits, and classes which are collectively called members. A class can hold members such as data members, member methods, constructors, blocks, nested classes, and information about the superclass.

Declaration of Class

A class can be declared with the class keyword, followed by a name of the class. There are some optional attributes that can be used with class declaration as mentioned below.

  • Class Keyword: A class keyword is used to declare the type of class.
  • Class Name: It should be written in an initial letter.
  • Body: The body of the class should be enclosed with curly braces{}.
class classname{ // methods }

Scala Objects

In Scala programming language, an object is the physical entity of a class which is interacted by invoking by the methods. The Scala object is represented by the following points.

  • Identity This is used to represent the name of an object.
  • Behaviour The behaviors of the object are defined by methods.
  • State It represents the state of an object.

Let us understand Scala class and object and its operations with the below example which will create a class with the name (classexample) and an object with the name (objectexample) and perform an action. Save the program with scalaclass.scala name and run it from the terminal by using scala scalaclass.scala command (refer screenshot).

import class classexample(val abc: Int, val xyz: Int) { var a: Int = abc var b: Int = xyz def datamove(fx: Int, yz: Int) { a = a + fx b = b + yz println ("Result 1 : " + a); println ("Result 2 : " + b); } } object objectexample { def main(args: Array[String]) { val pt = new classexample(100, 200); pt.datamove(50, 50); } }



Click Here To Download Code File.