Open In App

Class and Object in Scala

Last Updated : 19 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities.

Class

A class is a user-defined blueprint or prototype from which objects are created. Or in other words, a class combines the fields and methods(member function which defines actions) into a single unit. Basically, in a class constructor is used for initializing new objects, fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.

Declaration of class 
In Scala, a class declaration contains the class keyword, followed by an identifier(name) of the class. But there are some optional attributes which can be used with class declaration according to the application requirement. In general, class declarations can include these components, in order: 

  • Keyword class: A class keyword is used to declare the type class.
  • Class name: The name should begin with a initial letter (capitalized by convention).
  • Superclass(if any):The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  • Traits(if any): A comma-separated list of traits implemented by the class, if any, preceded by the keyword extends. A class can implement more than one trait.
  • Body: The class body is surrounded by { } (curly braces).

Syntax:  

class Class_name{
// methods and fields
}

Note: The default modifier of the class is public. 

Example:  

Scala




// A Scala program to illustrate
// how to create a class
 
// Name of the class is Smartphone
class Smartphone
{
     
    // Class variables
    var number: Int = 16
    var nameofcompany: String = "Apple"
     
    // Class method
    def Display()
    {
        println("Name of the company : " + nameofcompany);
        println("Total number of Smartphone generation: " + number);
    }
}
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
        // Class object
        var obj = new Smartphone();
        obj.Display();
    }
}


Output: 

Name of the company : Apple
Total number of Smartphone generation: 16

Objects

It is a basic unit of Object Oriented Programming and represents the real-life entities. A typical Scala program creates many objects, which as you know, interact by invoking methods. An object consists of :  

  • State: It is represented by attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

Consider Dog as an object and see the below diagram for its identity, state, and behavior.  

Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”. 
 

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. 

In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: 

Syntax:  

var obj = new Dog();

Scala also provides a feature named as companion objects in which you are allowed to create an object without using the new keyword.  

Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor. 

Example:  

Scala




// A Scala program to illustrate the
// Initialization of an object
 
// Class with primary constructor
class Dog(name:String, breed:String, age:Int, color:String )
{
        println("My name is:" + name + " my breed is:" + breed);
        println("I am: " + age + " and my color is :" + color);
     
}
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
        // Class object
        var obj = new Dog("tuffy", "papillon", 5, "white");
    }
}


Output: 

My name is:tuffy my breed is:papillon
I am: 5 and my color is :white

Explanation: This class contains a single constructor. We can recognize a constructor because in Scala the body of a class is the body of the constructor and parameter-list follows the class name. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, ”papillon”, 5, ”white” as values for those arguments:

var obj = new Dog("tuffy", "papillon", 5, "white");

The result of executing this statement can be illustrated as : 

Anonymous object

Anonymous objects are the objects that are instantiated but does not contain any reference, you can create an anonymous object when you do not want to reuse it. 

Example:  

Scala




// Scala program to illustrate how
// to create an Anonymous object
 
class GFG
{
    def display()
    {
        println("Welcome! GeeksforGeeks");
    }
}
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
        // Creating Anonymous object of GFG class
        new GFG().display();
    }
}


Output: 

Welcome! GeeksforGeeks

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads