Object Example

The following example creates an IDL object class with both instance and static methods.

The ObjCircle class inherits from the IDL_Object superclass. To run the example, save the following code into a file called "objcircle__define.pro" somewhere on IDL's path.

FUNCTION ObjCircle::Init, _EXTRA=ex

COMPILE_OPT IDL2

; Call our superclass Initialization method.

void = self->IDL_Object::Init()

IF (ISA(ex)) THEN self->SetProperty, _EXTRA=ex

RETURN, 1

END

 

PRO ObjCircle::Cleanup

COMPILE_OPT IDL2

; Call our superclass Cleanup method

self->IDL_Object::Cleanup

END

 

FUNCTION ObjCircle::Area

COMPILE_OPT IDL2

RETURN, !const.pi*self.radius^2

END

 

FUNCTION ObjCircle::GetCircles

; Static method.

; Note: Cannot use "self" within a static method

COMPILE_OPT IDL2, static

obj = OBJ_VALID(COUNT=c)

RETURN, obj[WHERE(OBJ_ISA(obj, 'ObjCircle'), /NULL)]

END

 

pro ObjCircle::Plot, _EXTRA=ex

compile_opt idl2

w = WINDOW()

p = ELLIPSE(self.center[0], self.center[1], $

MAJOR=self.radius, _EXTRA=ex)

end

 

PRO ObjCircle::GetProperty, $

CENTER=center, PI=pi, RADIUS=radius

; This method can be called either as a static or instance.

COMPILE_OPT IDL2, static

; If "self" is defined, then this is an "instance".

IF (ISA(self)) THEN BEGIN

; User asked for an "instance" property.

IF (ARG_PRESENT(center)) THEN center = self.center

IF (ARG_PRESENT(radius)) THEN radius = self.radius

endif else begin

; User asked for a "static" property.

IF (ARG_PRESENT(pi)) THEN pi = !const.pi

ENDELSE

END

 

PRO ObjCircle::SetProperty, CENTER=center, RADIUS=radius

COMPILE_OPT IDL2

; If user passed in a property, then set it.

IF (ISA(center)) THEN self.center = center

IF (ISA(radius)) THEN self.radius = radius

END

 

PRO ObjCircle__define

COMPILE_OPT IDL2

void = {ObjCircle, $

inherits IDL_Object, $ ; superclass

center: [0d, 0d], $ ; two-element array

radius: 0d} ; scalar value

END

After the above code is saved, you can then execute the following lines of code to try out your new ObjCircle class:

COMPILE_OPT IDL2

; Create an object instance.

a = ObjCircle()

 

; Set properties

a.center = [50, 60]

a.radius = 20

 

; Retrieve some instance data

PRINT, a.center

 

; Create another instance.

b = ObjCircle(CENTER=[100,200], RADIUS=40)

 

; Call an instance function method.

PRINT, b.Area()

 

; Call a static method.

obj = ObjCircle.GetCircles()

PRINT, obj

 

; Retrieve a static property

PRINT, ObjCircle.Pi

 

; Delete the objects

a = 0

b = 0

obj = 0

Note that in all of the methods and procedures above, we used compile_opt idl2 to avoid any confusion between the use of parentheses for array indexing versus function calls. See Static Methods for more details on the use of compile_opt.