Fields and Accessors
The fields for a class are denoted using the @ symbol, but otherwise work like regular variables.
// a class with no methods
class Point
def new()
@x = 0
@y = 0
end
def setLocation(x, y)
@x = x
@y = y
end
def move(x, y)
@x = @x + x
@x = @y + y
end
def getX()
return @x
end
def getY()
return @y
end
end
point = new Point()
point.setLocation( 10, 10 )
point.move( 0, 5 ) // point is now at 10, 15They are defined when a value is set to them.
Accessors
Fields are fully private, they cannot be accessed outside of a class, or even in sub and super classes. In order to access, or modify them, you need to do this yourself.
class Point
def new(x, y)
@x = x
@y = y
end
def getX()
return @x
end
def setX( x )
@x = x
end
endAs this is a very common task, Quby provides several accessors for generating methods. These include:
- get - for reading the value, with a method that starts with 'get'
- set - for writing to the value, with a 'set' prefix
- getset - for generating both a 'get' and a 'set' method
- read - generates a reading method, with the same name as the field
- write - generates a writing method, with the same name as the field
- attr - generates both a 'read' and a 'write' method.
The accessors are used in the body of the class definition, and cannot be used in functions or method (as they are evaluated at compile time).
class Point
// generates the method 'getX()'
get( x )
// generates the method 'setX( newX )'
set( x )
def new(x, y)
@x = x
@y = y
end
end
p = new Point( 4, 8 )
x = p.getX()
p.setX( 10 )The code above generates 'getX()', and 'setX( newX )' methods automatically.
The 'get', 'set' and 'getset' generates all prefix 'get' or 'set' accordingly. If you don't like using that, then you can use 'read', 'write' and 'attr' to do the same, but have no prefix.
class Point
// generates the method 'x()'
read( x )
// generates the method 'x( newX )'
write( x )
def new(x, y)
@x = x
@y = y
end
end
p = new Point( 4, 8 )
x = p.x()
p.x( 10 )You can also generate multiple methods by placing multiple fields in the accessor generators:
class Point
// generates methods 'getX()' and 'getY()'
get( x, y )
// generates methods 'setX( newX )' and 'setY( newY )'
set( x, y )
def new(x, y)
@x = x
@y = y
end
end
p = new Point( 4, 8 )
x = p.getX()
p.setX( 10 )
y = p.getY()
p.setY( 5 )The 'getset' version of the above would be:
class Point
// generates methods 'getX()', 'getY()',
// 'setX( newX )' and 'setY( newY )'
getset( x, y )
def new(x, y)
@x = x
@y = y
end
end
p = new Point( 4, 8 )
x = p.getX()
p.setX( 10 )
y = p.getY()
p.setY( 5 )