Scala Object and Class
Unlike java, scala is a pure object oriented programming language. It allows us to create object and class so that you can develop object oriented applications.
Object is a real world entity. It contains state and behavior. Laptop, car, cell phone are the real world objects. Object typically has two characteristics:
1) State: data values of an object are known as its state.
2) 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.
Class is a template or a blueprint. It is also known as collection of objects of similar type.
In scala, a class can contain:
You must initialize all instance variables in the class. There is no default scope. If you don't specify access scope, it is public. There must be an object in which main method is defined. It provides starting point for your program. Here, we have created an example of class.
Scala Sample Example of Class
Scala Sample Example2 of Class
In scala, you can create class like this also. Here, constructor is created in class definition. This is called primary constructor.
Scala Example of class that maintains the records of students
101 Raju 102 Martin
Scala Anonymous object
In scala, you can create anonymous object. An object which has no reference name is called anonymous object. It is good to create anonymous object when you don't want to reuse it further.
Scala Anonymous object Example
Sum = 20