JAVA DEVELOPER SITE
 

Scala - Classes & Objects


In this chapter Scala - Classes & Objects If you understanding on Java it will pretty easy to learn Scala syntax

Object

It contains state and behavior. TV, Smart Phone,Laptop are the real world objects. Object typically has two characteristics:

  • State : data values of an object are known as its state
  • Behavior: functionality that an object performs is known as its behavior.

Object in scala is an instance of class. It is also known as runtime entity.

Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object

Class

Class is a template. It is also known as collection of objects of similar type. inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor.

Scala Example1 of Class

    class Student{  
        var id:Int = 5;                         // All fields must be initialized  
        var name:String = null;  
    }  
    object MainObject{  
        def main(args:Array[String]){  
            var s = new Student()               // Creating an object  
            println(s.id+" "+s.name);  
        }  
    }  
Output: 5 null

Scala Example2 of Class

In scala, you can create class like this also. Here, constructor is created in class definition.
    class Student(id:Int, name:String){     // Primary constructor  
        def show(){  
            println(id+" "+name)  
        }  
    }  
    object MainObject{  
        def main(args:Array[String]){  
            var s = new Student(50,"David")   // Passing values to constructor  
            s.show()                // Calling a function by using an object  
        }  
    }  
Output: 50 David

Scala Example of class that maintains the records of Animals

    class Student(id:Int, name:String){  
        def getRecord(){  
            println(id+" "+name);  
        }  
    }  
      
    object MainObject{  
        def main(args: Array[String]){  
            var student1 = new Animals(11,"Cat");  
            var student2 = new Animals(12,"Dog");  
            student1.getRecord();  
            student2.getRecord();  
        }  
    }  

Output
11 Cat
12 Dog


Scala Anonymous object

In scala, you can create anonymous object. An object which has no reference name is called anonymous object.

Scala Anonymous object Example

    class Arithmetic{  
        def add(a:Int, b:Int){  
            var sub = a-b;  
            println("sub = "-sub);  
        }  
    }  
      
    object MainObject{  
        def main(args:Array[String]){  
            new Arithmetic().add(40,35);  
      
        }  
    }  
Output sub = 5