Inner classes
- Definition
In object-oriented programming, an inner or nested class is a class declared entirely within the body of another class or interface.
It is not the same as a subclass which is a class which inherits members from another class or classes and can be declared anywhere the parent class(es) are within scope. However, inner classes may nevertheless be subclasses of other classes as well.
- Task
If your language supports the object oriented paradigm, explain what support it has for inner classes and, if there is no support, what if anything can be done to simulate them.
Illustrate your answer by creating an inner class with a constructor, an instance method and field and show how to instantiate it.
If you language does not support the object oriented paradigm, you may either omit this task or describe (and substitute in your example) any equivalent structure(s) which the language does have.
- Reference
- Related task
Wren
Strictly speaking, Wren does not support inner classes.
However, it is possible to declare a class within either a method or function and we can use this feature to simulate an inner class.
To make things a little more interesting the inner class in the following example also inherits from the outer class.
class Outer {
static makeInner {
class Inner is Outer {
construct new(field) {
super(field + 1) // call parent class constructor
_field = field
}
method {
System.print("Inner's field has a value of %(_field)")
outerMethod
}
}
return Inner
}
construct new(field) {
_field = field
}
outerMethod {
System.print("Outer's field has a value of %(_field)")
}
}
var Inner = Outer.makeInner
var inner = Inner.new(42)
inner.method
- Output:
Inner's field has a value of 42 Outer's field has a value of 43