OOP is all about identifying aspects of your project that can be implemented as objects. An object is usually a noun (e.g. fruit, animal, machine) with Properties (e.g. colour) Methods (e.g. delete) and sometimes Events (e.g. LostFocus).
Although "Class" in general programming can mean just a bunch of code in a module, in OOP a Class is the code you write as a kind of template from which you create Objects.
So here is a simple "fruit" example; Start a new project and then right-click in the Project window and select New > Class... and name it "clsFruit.class".
Another principle of OOP is encapsulation. We usually hide the internal class properties from the outside world and use "Getter" functions & "Setter" functions to read & write them. So even in our simple example, we need to Declare in the clsFruit.class any properties that we want to make available. Initially we need a Property called "Name" and another called "Colour" :-
' Gambas class fileclsFruit.class
'external refs
Property Name As String 'the fruit Name
Property Colour As String 'the fruit Colour
...then we create Private properties:-
'internal refs
Private sFName As String 'the fruit Name
Private sFColour As String 'the fruit Colour
...then we create Getter & Setter functions:-
'Getter functions
Private Function Name_Read() As String
Return sFName
End
Private Function Colour_Read() As String
Return sFColour
End
'Setter functions
Private Sub Name_Write(Value As String)
sFName = Value
End
Private Sub Colour_Write(Value As String)
sFColour = Value
End
At this stage our class doesn't do much, but we can use it.On the main project form add this code to create a new instance of our class:-
Public myApple As New ClsFruit
Note: If autocomplete is working on your system, you should see the class name and properties listed as you type.Now add a Button and add this as its click event:-
Public Sub Button1_Click()
myApple.Name = "apple"
myApple.Colour = "red"
Me.Text = "I have a " & myApple.Colour & " juicy " & myApple.Name
myApple.
End
So you should now have a working example. You can create as many objects as you like from this new class, for example:-
Public myOrange As New ClsFruit
Public myPlum As New ClsFruit
Public myBanana As New ClsFruit
...and each instance can be given its own unique name & colour.If this is of interest to anyone, I'm happy to write more.