[Gambas-user] Static Classes and Modules

Tobias Boege taboege at ...626...
Sat Sep 20 11:22:30 CEST 2014


On Sat, 20 Sep 2014, John Leake wrote:
> Hi All,
> Could someone please clarify the characteristics of a static class.
> 
> My understanding of Static Classes from other languages is:
> 
> They cannot be created or more precisely no more than one instance of
> the class can exist. This means that if a process alters the state of
> the class then that changed state is seen by all other processes that
> hold a reference to that class.
> 

That's what static means in Gambas, too. There is only the discrepancy with
creating objects from static classes of which we don't know why it exists.

A static property (in a class definition) is shared by all objects of that
class. A static method must not refer to dynamic symbols of the class, i.e.
must be executable without object context.

> In Ruby for example, the same behaviour is achieved through Class
> methods and Class variables ie they act on the class itself and not on
> instances of that class.  Here multiple instances of a class have their
> own state but if any one instance of that class changes the state of a
> class variable then all instances of that class will see that change.
> 
> >From the docs;
> "In Gambas, a static class is also named a module.
> 
> A static class cannot be instantiated: it would create an object with no
> dynamic variable, which is useless."
> 
> So could someone tell me if a class without any dynamic variable ie a
> static class, can or cannot be created ?
> 

Or you can try it out.

What I did was creating a module and making objects from it with New -- it
works, but those objects are even more limited than I had expected. In their
code, there seems to be no way to even see that they are any different from
the automatic instance (singleton). The module's code was:

--8<--[ Module1.module ]----------------------------------------------------
' Gambas module file

Public Sub Print()
  Print Me
End
--8<------------------------------------------------------------------------

and the program:

--8<--[ MMain.module ]------------------------------------------------------
' Gambas module file

Public Sub Main()
  Dim h As New Module1, g As New Module1

  Print Module1
  Module1.Print()
  Print "---"
  Print h
  h.Print()
  Print "---"
  Print g
  g.Print()
End
--8<------------------------------------------------------------------------

with the output:

  (Class Module1)
  (Class Module1)
  ---
  (Module 0x...b8)
  (Class Module1)
  ---
  (Module 0x...e8)
  (Class Module1)

So indeed, there are different objects (especially, it's possible to
instantiate modules) but "Me" inside the module code always refers to
the singleton.

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk




More information about the User mailing list