Scala – Encapsulation

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

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 is bound to the outer object.

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
Welcome 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
  

Quick Support

image image