We have been exploring the Ring Programming Language in the last two articles. Ring is a dynamic programming language with many interesting features. In today’s article, let us try to understand how this dynamic behavior is reflected in Classes and Objects.
In Ring, we can define classes at runtime. One way to do this is to execute a “script”. As part of the script, we can define a class, and so when the script is executed, the class gets “defined”.
Look at the code fragment below:
When we execute this code, this is the output:
Being able to define classes at runtime is definitely interesting. What happens if we redefine this class, say, with a different structure?
That is not allowed! This results in an error at runtime:
Next, let us dynamically define another class that has a single method, and then invoke that method:
Here is the output:
What if we try to invoke a method that is not defined in the class?
Here is the runtime error:
This is along expected lines.
Reflection
Ring has an interesting “Reflection” API. I am going to touch upon just three functions today. For more information, you can go through this article.
The first function we will consider is “methods()”. Given an object as argument, this function returns a list of methods supported by the object. We can then invoke the “discovered” methods.
This is the output:
No surprise here.
Next, using the “addmethod()” function, we can add a new method to an object. Likewise, there is an “addattribute()” function to add an attribute to an object:
And the output is:
What is peculiar and important to keep in mind is that we are not adding the method and attribute to the “DynamicClass2” class, but only to a single instance of that class. This implies that if we create another object of this class and try to access the method or attribute that we just now added to the other object, we will get an error!
Here is a code fragment that shows this:
Here is the corresponding output:
It is clear that Ring differs from other popular languages in the way Classes and Objects are handled.
We will continue to explore other features of Ring in future articles. Here is the code used in today’s article.
Have a nice weekend!
Recent Comments