Unlike java and other oops languages, scala is a pure object oriented programming language.
It allows us to create object and class as follow rules of OOPS Concept so
that you can develop object oriented applications.
Object is a real world entity. It contains state and attribute as well behavior or nature of entity. Laptop, car, cell phone are the real world objects.
Object typically has two characteristics:
To conclude, Object is blue print of Class . We are going to implement this class in below example.
We are created Student class and class members.
we define object and invoke main method.
An object in Scala is a special construct that represents a singleton instance of a class.
It is created using the object keyword in our code "MainObject".
class Student{
var id:Int = 0; // 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);
}
}
As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class.
In Scala, the constructor is used to create new objects.
class Person(name: String, age: Int, salary : Int) {
// Fields
private val fullName: String = s"Mr/Ms. $name"
// Method
def myGreet(): Unit = {
println(s"Hello, my name is $fullName, and I am $age years old.")
}
}
object PersonApp {
def main(args: Array[String]): Unit = {
val person = new Person("Alice", 30)
person.myGreet()
}
}
object Implicits {
implicit class StringEnhancer(original: String) {
def exclamationify(): String = s"$original!"
def repeat(n: Int): String = original * n
}
}
object DevloperIndiaDemo {
import Implicits._
def main(args: Array[String]): Unit = {
val message = "Hello, this is developer Indian "
val exclamationMyMessage = message.exclamationify()
println(exclamationMyMessage) // Output: "Hello, this is developer Indian"
val repeatedMyMessage = message.repeat(2)
println(repeatedMyMessage) // Output: "Hello, this is developer Indian Hello, this is developer Indian "
}
}
class Student(private val value: Int , ) {
def getValue: Int = value
// Other methods and code for the class...
}
object Student {
// Factory method to create instances of Student
def apply(value: Int): Student = new Student(value)
// Utility method provided by the companion object
def myValue(a: Int, b: Int): Int = a + b
}
val obj1 = Student(42) // Equivalent to Student.apply(42)
val obj2 = Student.apply(10) // Creating instances using the factory method
val sum = Student.myValue(5, 7) // sum will be 12