Object Oriented Programming in Scala
The Inner class means characterizing a class into another. This element empowers the users to sensibly bunch classes that are just utilized in one place, subsequently this expands the utilization of encapsulation, and make more creatable and viable code. In Scala, the idea of inner classes is not the same as Java. Like in Java, the inner class is the member from the external class, yet in Scala, the internal class to the outer object.
Object-Oriented Programming (OOP) is a foundational paradigm in Scala that emphasizes the organization of code into classes and objects, promoting encapsulation, inheritance, and polymorphism. Scala seamlessly combines functional and object-oriented programming concepts, providing a powerful and expressive language for building modular and extensible applications.
In Scala, classes serve as blueprints for creating objects, which encapsulate state (fields) and behavior (methods). Scala supports single and multiple inheritance through traits, enabling code reuse and flexibility in class hierarchies. Traits provide a mechanism for composing behaviors independently of class inheritance.
Scala’s type system supports subtype polymorphism, allowing methods to be overridden in subclasses to provide specialized implementations. Furthermore, Scala encourages immutability and composition over inheritance, promoting a more flexible and robust design approach.
Use case 1:
// Outer class
class prwatech {
// Inner class
class P1
{
var a = 1
def method()
{
for(a<-0 to 2)
{
println("Welcome to Prwatech Data Science");
}
}
}
}
object Main
{
def main(args: Array[String])
{
// Creating object of the outer and
// inner class Here, P1 class is
// bounded with the object of Prwatech class
val obj = new prwatech();
val o = new obj.P1;
o.method();
}
}
Output
Welcome to Prwatech Data Science
2Welcome to Prwatech Data Science
Welcome to Prwatech Data Science
Use case 2:
// Class inside Object
class outer_class_Prwatech
{
object inner_object_Prwatech1
{
val a = 0;
def method()
{
for(a <- 1 to 2)
{
println("object inside a class Prwatech")
}
println()
}
}
}
// Object inside Class
object outer_objectPrwatech
{
class innerPrwatech
{
val b = 0;
def method()
{
for(b <- 1 to 2)
{
println("class inside an object Prwatech")
}
}
}
}
object Main
{
// Main method
def main(args: Array[String])
{
// Object inside a class
new outer_class_Prwatech().inner_object_Prwatech1.method;
// Class inside an object
new outer_objectPrwatech.innerPrwatech().method;
}
}
Output
object inside a class Prwatech
object inside a class Prwatech
class inside an object Prwatech
class inside an object Prwatech
Use case 3:
class Prwatech
{
// Inner class
class P1
{
var x = 1
def method()
{
for(x<-0 to 0 )
{
println("Welcome to Prwatech");
}
}
}
}
object Main
{
def main(args: Array[String])
{
val obj = new Prwatech();
val o = new obj.P1;
o.method();
}
}
Output:
Welcome to Prwatech