I am beginner to java and was trying out this code puzzle from the book head first java which I solved as foll开发者_高级运维ows and got the output correct :D
class DrumKit
{
boolean topHat=true;
boolean snare=true;
void playSnare()
{
System.out.println("bang bang ba-bang");
}
void playTopHat()
{
System.out.println("ding ding da-ding");
}
}
public class DrumKitTestDriver
{
public static void main(String[] args)
{
DrumKit d =new DrumKit();
if(d.snare==true)
{
d.playSnare();
}
//d.snare=false;
d.playTopHat();
}
}
Output is ::
bang bang ba-bang ding ding da-ding
Now the problem is that in that code puzzle one code snippet is left that I did not include..it's as follows
d.snare=false;
Even though I did not write it , I got the output like the book. I am wondering why is there need for us to set it's value as false even when we know the code is gonna run without it too !??
I am wondering what the coder had in mind ..I mean what could be the possible future use and motive behind doing this ?
I am sorry if it's a dumb question. I just wanna know why or why not to include that particular statement ? It's not like there's a loop or something that we need to come out of. Why is that statement there ?
It's probably just there to demonstrate how to change a public member variable.
where is
d.snare=false;
If it is before the if condition then it would change the output by affecting state of the variable inside class d, it would now just post.
ding ding da-ding The if condition would be bypassed, however if it is after the if condition, it will not have any effect since its value is evaluated only in the if condition.
written in Main or inside the class;
From the code you have posted the output is correct.
I'm quite sure there is NO reason to change a variable/state/whatever if it is definitive not used afterwards!
Regards
You should let DrumKit handle the logic and let the main class just do the settings on DrumKit. Something like this:
class DrumKit
{
boolean topHat=true;
boolean snare=true;
void playSnare() {
System.out.println("bang bang ba-bang");
}
void playTopHat() {
System.out.println("ding ding da-ding");
}
void play(){
if (snare){
playSnare();
}
if (topHat){
playTopHat();
}
}
}
public class DrumKitTestDriver {
public static void main(String[] args) {
DrumKit d =new DrumKit();
d.snare = false;
d.play();
}
}
精彩评论