Forging The Rings!
From Huben's Wiki
Line 25: | Line 25: | ||
} | } | ||
</pre> | </pre> | ||
− | Constructors such as this one are methods with arguments. The arguments are variables. Their values are set when the constructor is called (right after a '''new''' keyword.) | + | Constructors such as this one are methods with arguments. This constructor could be called with: '''Ring oneRing = new Ring("gold", "Sauron");''' |
+ | The arguments are variables. Their values are set when the constructor is called (right after a '''new''' keyword.) theMetal is set to "gold" and whom is set to "Sauron". | ||
Setting the metal and givenTo fields with the values of the arguments is obvious. But the subtle thing is that the class variable numberForged, which started at zero, is now increased by one every time this constructor is called, which means for every ring instance created. We are counting the number of rings created! | Setting the metal and givenTo fields with the values of the arguments is obvious. But the subtle thing is that the class variable numberForged, which started at zero, is now increased by one every time this constructor is called, which means for every ring instance created. We are counting the number of rings created! | ||
+ | |||
+ | Let us now show how this is used to forge rings! | ||
+ | |||
+ | == Building The Forge == | ||
+ | <pre> | ||
+ | class Forge | ||
+ | { | ||
+ | static public void main (String[] args) | ||
+ | { | ||
+ | Ring oneRing = new Ring("gold", "Sauron"); | ||
+ | Ring[3] elvenRing; // Array of 3 rings for elves. | ||
+ | elvenRing[0] = new Ring("silver", "elf"); | ||
+ | elvenRing[1] = new Ring("silver", "elf"); | ||
+ | elvenRing[2] = new Ring("silver", "elf"); | ||
+ | } | ||
+ | } | ||
+ | </pre> |