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
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
Class is a template or a blueprint. It is also known as collection of objects of similar type.
In scala, a class can contain:
- Data member
- Member method
- Constructor
- Block
- Nested class
- Super class information etc.
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
Output:
0 null
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.
Output:
100 Martin
Scala Example of class that maintains the records of students
Output:
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
Output:
Sum = 20