Forging The Rings!
From Huben's Wiki
Line 28: | Line 28: | ||
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". | 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. The metal field will never be able to be set again for this instance, because it is final. 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! |
Add a toString() method to write: "I am a X ring, made for Y." X should be the metal field, Y should be the givenTo field. | Add a toString() method to write: "I am a X ring, made for Y." X should be the metal field, Y should be the givenTo field. | ||
Line 46: | Line 46: | ||
System.out.println(Ring.forged()); | System.out.println(Ring.forged()); | ||
Ring[] elvenRing = new Ring[3]; // Array of 3 rings for elves. | Ring[] elvenRing = new Ring[3]; // Array of 3 rings for elves. | ||
+ | System.out.println(Ring.forged()); | ||
+ | System.out.println(elvenRing[0]); | ||
elvenRing[0] = new Ring("silver", "an elf"); | elvenRing[0] = new Ring("silver", "an elf"); | ||
elvenRing[1] = new Ring("silver", "an elf"); | elvenRing[1] = new Ring("silver", "an elf"); | ||
Line 51: | Line 53: | ||
System.out.println(oneRing); | System.out.println(oneRing); | ||
System.out.println(elvenRing[0]); | System.out.println(elvenRing[0]); | ||
− | System.out.println(elvenRing[1]); | + | System.out.println(elvenRing[1].toString()); |
System.out.println(elvenRing[2]); | System.out.println(elvenRing[2]); | ||
System.out.println(Ring.forged()); | System.out.println(Ring.forged()); | ||
Line 57: | Line 59: | ||
} | } | ||
</pre> | </pre> | ||
+ | Let's understand what's happening in Forge.main(). Forge.main() is a static method. Without an instance variable of something, it can only call other static methods: such as Ring.forged(). | ||
+ | * The first time we call Ring.forged(), it shows that 0 have been forged. | ||
+ | * The oneRing instance is created by calling the constructor and setting the constructor argument theMetal to "gold" and whom to "Sauron". | ||
+ | * Now when we call Ring.forged(), it shows that 1 ring has been forged. |