Forging The Rings!
From Huben's Wiki
Line 29: | Line 29: | ||
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! | ||
+ | |||
+ | 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 static forged() method that returns the String "There have been N rings forged." N should be numberForged. | ||
Let us now show how this is used to forge rings! | Let us now show how this is used to forge rings! | ||
Line 38: | Line 42: | ||
static public void main (String[] args) | static public void main (String[] args) | ||
{ | { | ||
+ | System.out.println(Ring.forged()); | ||
Ring oneRing = new Ring("gold", "Sauron"); | Ring oneRing = new Ring("gold", "Sauron"); | ||
+ | System.out.println(Ring.forged()); | ||
Ring[3] elvenRing; // Array of 3 rings for elves. | Ring[3] elvenRing; // Array of 3 rings for elves. | ||
− | elvenRing[0] = new Ring("silver", "elf"); | + | elvenRing[0] = new Ring("silver", "an elf"); |
− | elvenRing[1] = new Ring("silver", "elf"); | + | elvenRing[1] = new Ring("silver", "an elf"); |
− | elvenRing[2] = new Ring("silver", "elf"); | + | elvenRing[2] = new Ring("silver", "an elf"); |
+ | System.out.println(oneRing); | ||
+ | System.out.println(elvenRing[0]); | ||
+ | System.out.println(elvenRing[1]); | ||
+ | System.out.println(elvenRing[2]); | ||
+ | System.out.println(Ring.forged()); | ||
} | } | ||
} | } | ||
</pre> | </pre> |