anyone who can tell me how to create objects when using a constructor and when NOT using a constructor?
Thanks on advance.
Kind regards.
anyone who can tell me how to create objects when using a constructor and when NOT using a constructor?
Thanks on advance.
Kind regards.
You have to use a constructor. If you do not define it, a default one is provided.
I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones.
Freedom is measured in Stallmans.
Projects: gEcrit
That is not necessarily true. The object may have one or more factory methods from which the object can be created. If you wish to create an object but the constructor is private, look in the documentation if there are any factory methods available.
what would the code look like? for example i have a little program, where i try to get better. The program is to make a machine that can give a refreshing drink when you put enough money in the machine.
And i'm having trouble to create a refreshing drink object. i cannot visualize it.
Where i then would put the drink in a array to track how many drinks are their, and such.
Any guides about object making?
What language are you programming in?
I suggest the following objects: a DrinkMachine and a Drink. The DrinkMachine could have a method called purchase with name and an amount of money.
The DrinkMachine could have a number called capacity which keeps track of the number of drinks in the machine. Whenever a drink is purchased, a Drink object could be created and returned to the caller of the purchase method.
Alternatively the DrinkMachine class could have an array of Drink objects. To fill the DrinkMachine class you could have a method:
add(Drink drink)
which adds a drink to the DrinkMachine (like when a real person is filling it up).
When someone buys a drink the purchase method would take an amount of money for the drink and if the amount is enough, the Drink object would be removed from the array in DrinkMachine, and the object would be returned from the function.
Paul
I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones.
Freedom is measured in Stallmans.
Projects: gEcrit
Yes, which means that you don't have to use a constructor to create an object. Sometimes objects can only be created by calling a factory method. Internally, a constructor is still used but a constructor is therefore not the only way to create an object (it can be private by design).
I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones.
Freedom is measured in Stallmans.
Projects: gEcrit
Bookmarks