Extend a BaseService component and add a version field to the child.
← Dependency Injection · Ref: Q1108
Mark parent 'as open' and extend with child:
BaseService as open serviceName <- "Base" default operator
ExtendedService extends BaseService version <- 1 default operator
Child inherits parent fields. 'default operator' covers both parent and child fields.
See Q1105 for basic components. See Q1080 for class inheritance with :=: copy.
Example
defines module qa.di.componentinheritance defines component BaseService as open serviceName <- "BaseService" default operator defines component ExtendedService extends BaseService version <- 1 default operator defines program ComponentInheritanceDemo() stdout <- Stdout() base <- BaseService() stdout.println(`Base: ${base}`) ext <- ExtendedService() stdout.println(`Extended: ${ext}`) stdout.println(`Extended set?: ${ext?}`)
Common mistakes
E05030 — Components are closed by default. Add 'as open' to allow extension.
Incorrect:
BaseService
Correct:
BaseService as open
Other ways to ask this
- I have a base component and need to create a specialised version with extra fields
- In Spring I'd extend a @Service class. Write the EK9 component inheritance
- Given a BaseService, create an ExtendedService that adds version tracking
- Build a component hierarchy with parent and child fields
Coming from another language?
Spring: extend a @Component class. Guice: bind subclass to parent interface. EK9: component extends with 'as open' on parent.
Keywords: inheritance, open, extends, parent, child, component