as a hobbyist programming beginner, I am trying to get into object-oriented programming. The aim being to be able to create programs with GUIs for Linux (in the long run).
Recently I discovered Gambas and have been playing around with objects and trying to learn their concepts and how they are created.
As I have come to understand, there seem to be different ways of how an object may be created in Gambas.
My questions are:
- When and why would I use Version 1 over the others?
- What are the implications of each version?
- Have I missed anything?
Inspired by SteveDee's great "A Dirty Guide to OOP #1" https://forum.gambas.one/viewtopic.php?f=4&t=816, I decided to also go with fruits for my examples
The Fruit-Class:
' Gambas class file
Property Name As String Use sName 'shorthand syntax for declaring the properties of a class,
Property Colour As String Use sColour 'setter and getter methods are created "under the hood", using the given variables.
The Main-Module:
Version 1
' Gambas module file
Public oApple As Fruit 'declaration of the object-variable outside of Sub Main()
Public Sub Main()
oApple = New Fruit 'creation of the object inside Sub Main()
'init the fruit
oApple.name = "Apple1"
oApple.colour = "Green"
'show what's happened
Print "Name: " & oApple.Name
Print "Colour: " & oApple.Colour
End
Version 2
' Gambas module file
Public Sub Main()
Dim oApple As New Fruit 'declaration of the object-variable and creation of the object inside of Sub Main()
'init the fruit
oApple.name = "Apple2"
oApple.colour = "Red"
'show what's happened
Print "Name: " & oApple.Name
Print "Colour: " & oApple.Colour
End
Version 3 a)
'Gambas module file
Public Sub Main()
Dim sClassName As String = "Fruit"
Dim oApple As Object = New (sClassName) As "Apple" 'declaration of the object-variable and creation of the object,
'using a variable for the class name; the >>As "Apple"<< bit is the event-handler
'init the fruit
oApple.name = "Apple3"
oApple.colour = "Yellow"
'show what's happened
Print "Name: " & oApple.Name
Print "Colour: " & oApple.Colour
End
Version 3 b)
'Gambas module file
Public Sub Main()
Dim sClassName As String = "Fruit"
Dim sObjectName As String = "Apple"
Dim oApple As Object = New (sClassName) As (sObjectName) 'using a variable also for the event-handler
'init the fruit
oApple.name = "Apple4"
oApple.colour = "Brown"
'show what's happened
Print "Name: " & oApple.Name
Print "Colour: " & oApple.Colour
End
Thanks for your help!Seb.