...
| Code Block |
|---|
class A{
final a(){ 11 }
def b(){ 12 }
}
final class B extends A{
//def a(){ 15 } //compile error when uncommented: can not override final A.a()
def b(){ 16 }
}
//class C extends B{} //compile error when uncommented: can not extend final C
|
Constructors
Just as a class's constructor can call another constructor at the beginning of its code, so also it can call a constructor on the superclass at the beginning of its code:
| Code Block |
|---|
class A{
def list= []
A(){
list<< "A constructed"
}
A(int i){
this()
list<< "A constructed with $i"
}
}
class B extends A{
B(){
list<< "B constructed"
}
B(String s){
super(5) //a constructor can call its superclass's constructor if it's
//the first statement
list<< "B constructed with '$s'"
}
}
def b1= new B('kea')
assert b1.list.collect{it as String} == [
"A constructed",
"A constructed with 5",
"B constructed with 'kea'",
]
def b2= new B()
assert b2.list == [
"A constructed",
//default parameterless constructor called if super() not called
"B constructed",
]
|
Using Classes by Extending Them
Some classes supplied with Groovy are intended to be extended to be used. For example, FilterInputStream, FilterOutputStream, FilterReader, and FilterWriter:
...
We can similarly extend FilterInputStream, FilterReader, and FilterWriter.
The Object Hierarchy
All classes are arranged in a hierarchy with java.lang.Object as the root. Here are those we've met so far; those labelled as such are abstract and final classes:
...