-
Notifications
You must be signed in to change notification settings - Fork 1
OOP
Liu Siwei edited this page Oct 15, 2017
·
12 revisions
YJLO Script supports OOP by using function closure
and function member reference
.
func Counter(name) {
/* member fields */
_name := name
_count := 0
/* member functions */
func getName() { return _name }
func getCount() { return _count }
func increase() { _count++ }
return func () {}
}
counter := Counter("My Counter") // instantiate a new Counter
print( counter.getName() ) // output "My Counter"
counter.increase()
counter.increase()
print( counter.getCount() ) // output 2
You can use class
keyword to simplify the above Counter function.
class Counter {
/* member fields */
_name := ""
_count := 0
/* constructor */
@(name) {
_name = name
}
/* member functions */
func getName() { return _name }
func getCount() { return _count }
func increase() { _count++ }
}
class DerivedClassName extends BaseClassName {
...
}
or
class DerivedClassName (BaseClassName) {
...
}
Example:
import Math
class Shape {
var _name = "Shape"
func getType() { return "Shape" }
func setName(name) { _name = name }
func getName() { return _name }
func getArea() { return 0 }
}
class Circle (Shape) {
setName("Circle")
var _radius = 1
func setRadius(radius) { _radius = radius }
func getArea() { return Math.round(Math.PI * _radius ** 2, 2) }
}
c := Circle()
c.setRadius(2)
print( c.getName() + " area: " + c.getArea() )
class Rectangle (Shape) {
setName("Rectangle")
var _width = 0
var _height = 0
func setWidth(width) { _width = width }
func setHeight(height) { _height = height }
func getArea() { return _width * _height }
}
r := Rectangle()
r.setWidth(4)
r.setHeight(10)
print( r.getName() + " area: " + r.getArea() )
class Square (Rectangle) {
setName("Square")
func setSide(side) {
setWidth(side)
setHeight(side)
}
}
s := Square()
s.setSide(5)
print( s.getName() + " area: " + s.getArea() )
/* output:
Circle area: 12.57
Rectangle area: 40
Square area: 25
*/
If a class extends multiple classes, only the first one is the parent, the rest are mixins.
There can be zero or one parent and an unlimited number of mixins.
For example,
class A { ... }
class B { ... }
class C { ... }
class D (A, B, C) {
...
}
Class A is the parent of D. B and C are mixins in D.
The difference between parent and mixin is that a child class only extends parent's environment instead of mixins'.
Classes used as mixins should not extend any other classes.
class C {
var name
func setName(name) {
this.name = name
return this
}
}
myC := C();
print( myC.setName("abc").name ) // => abc
Introduction
Langauge Guide
Libraries
- Utility
- ListUtil
- StringUtil
- Math
- Data Structure
- LinkedList
- Stack
- Heap
- HeapList
- HashMap
- HashSet
- Others
- UnitTest
- Tokenizer
Dev Reference
- Syntax Sugar