How does Scala handle inner classes differently to Java's nested, static or non-static, classes?
1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.
Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
inner class: Can only exist withing the instance of its enclosing class. Has access to all members. local class: class declared in a block. It is like an inner class (has access to all members) but it also has access to local scope.
The major difference is that if you have
class Outer {
class Inner {
def foo(x: Inner): Inner = this // just for the example below
}
}
and two instances of Outer
:
val a = new Outer
val b = new Outer
then a.Inner
and b.Inner
are two different types (where in Java they'd both be Outer.Inner
), so that you can't do
val aInner = new a.Inner
val bInner = new b.Inner
aInner.foo(bInner)
They do have a common supertype which is written Outer#Inner
.
Scala has proper nested classes, just like they were originally invented in Beta. Java's inner classes are not nested classes. The main difference is that nested classes are nested in the enclosing object, not merely an inner class inside the enclosing class. IOW: a nested class is a runtime instance property of an object of the enclosing class, and just like two different instances of the same class have identically named but different valued instance variables (fields), they also have identically named but different valued nested classes.
IOW, foo.SomeInnerClass
and bar.SomeInnerClass
are different classes and not type-compatible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With