Home »
Scala
Inner Class in Scala: How to create inner class?
By IncludeHelp Last updated : November 07, 2024
Inner Class
Inner Class is a special concept in Scala using which we can create a class inside another class. It is used for grouping together classes to improve the usability of the concept of encapsulation in Scala.
Though Scala inherits many features from Java but, the binding of inner classes. The inner class in Scala is bound to outer object.
Types of Inner Class Definitions
In Scala, they can be different types of inner class definitions,
- Creating a class inside another class
- Creating a class inside an object
- Creating an object inside a class
Before learning about the inner class, it would be good to revise these topics:
1) Creating a class inside another class
We can define a class inside another class. Accessing the inner class member will require creating the object of inner class using the object of outer class.
Syntax
class outerClass{
class innerClass{
// members of innerClass
}
}
Example
Illustrating the working of the inner class, creating a class inside another class,
// Illustrating the working of inner class
class outerClass{
class innerClass{
def printVal() {
println("This is inner Class from Outer Class!")
}
}
}
object myObjects {
def main(args: Array[String]) {
val outObj = new outerClass()
val inObj = new outObj.innerClass
inObj.printVal
}
}
Output:
This is inner Class from Outer Class!
2) Creating a class inside an object
We can define a class inside an Object. And accessing class needs object for creation.
Syntax
new outerObject.innerClass().member
Example
// Illustrating the working of inner class,
// Creating inner class inside outer Object...
object OuterObject{
class innerClass{
def printVal() {
println("This is inner Class from Outer Object!")
}
}
}
object myObjects {
def main(args: Array[String]) {
val inObj = new OuterObject.innerClass()
inObj.printVal
}
}
Output:
This is inner Class from Outer Object!
3) Creating an object inside a class
We can define an Object inside a class in Scala. And accessing object needs to create object of the outerClass.
Syntax
new outerClass().innerObject.member
Example
// Illustrating the working of inner class,
// Creating inner object inside outer class...
class outerClass{
object innerObject{
def printVal() {
println("This is inner Object from Outer Class!")
}
}
}
object myObjects {
def main(args: Array[String]) {
val inObj = new outerClass().innerObject
inObj.printVal
}
}
Output:
This is inner Object from Outer Class!