Classes Extended - jpbubble/NIL-isn-t-Lua GitHub Wiki
NIL has support for extended classes
General concept
class C1
int a=20
int b=30
end
class C2 extends C1
int a=25
int c=40
end
var C
C = new C2
print(C2.a,C2.b,C3.c)
// Output: 25, 30, 40
By extending a class, all members of the original are copied in, they can be overridden (like I did with member "a") or be left original (as done with "b") or even new members can be added (like "c").
Abstract
Abstracts MUST be overridden. A class containing abstracts is considered as "unfinished", so they must be extended in order to be used. Static members in the same class can be used though.
class C1
abstract void Hello()
int a = 20
void Bye()
print("Goodbye")
end
end
var c
// c = new C1 // Put as a comment, as this line would case an error as "Hello" is an abstract.
class C2 extends C1
void Hello()
print("Hello World")
end
end
c = new C2 // This one is fine... The abstract was overridden in the extension!
print(c.a) // 20
c.Hello() // "Hello World"
c.Bye() // "Goodbye"
One note, abstracts cannot be used on static members!
# Final members
Now "abstract" forces you to override a member in the extension... "final" forbids it.
class C1 void Hi() print("Hi") end
final void Bye() print("Bye") end end
class C2 extends C1 // This is no problem! Hi was not final! void Hi() print("Bonjour") end
// This will throw an error, as Bye was final!
void Bye()
print("Au revoir!")
end
end
Extending on groups and modules
groups and modules should not be extendable themselves, and best is not to even try. Groups and modules can however be extensions of classes.
class Base
int i = 20
void Hello()
print("Hello World!")
end
end
group Ex extends Base
int j = 30
end
print(Ex.i,Ex.j)
Ex.Hello()
Constructors and destructors in extended classes
If found they'll be called accordingly. If only one exists in in the base class, that one will be called, if one is present in the extended class, that one will override the base version. The keywords "final" and "abstract" should also have the same effect on a constructor or a destructor. Apart from them being called whenever a class is being created or destroyed, they are just normal methods like any other.