Some background: I'm reading "Head first Java 2nd edition" and I'm going through the examples which is showing me how to change the state of an object. The original code looks like the code below, however the previous chapter went over creating array's of an object, so I created an array of the object "Dog" and wanted to re-write it this way. To my understanding, it should work but it's giving me that error when I execute it. The error itself isn't very clear, if I could get a line number pointed to, that would help.
I'm not not sure about shortening it. Shortening code rarely helps with readability or maintainability.
As for improving it, I wouldn't have one dog class that acts like 3 different types of dog depending on a size parameter. You should have different types of Dog class extending Dog (or implementing a suitable interface) and then you create the appropriate instance depending on the size of Dog you want. Each type of dog class would then only have code to make the sound that type of dog would make.
In your DogTestDrive class you have a while loop that iterates from 0 to 2, but you're handling each value that you are iterating over with a special if statement. Why not scrap the loop and just initialize all three dogs one after another?
Also, the if statements in your while loop are misleading, the cases cover x values 1, 2, and else...which I would naturally assume is 3 but is actually zero.
If, after you have created all your dog instances, you want to go over all of them and bark(), this would be the perfect place to use a for loop or the enhanced for loop.
For the Dog class, you could add a constructor that takes the size instead of creating the dog and then setting the size in two steps. Then add a getSize() and setSize() method and adjust the dog's size through that. Generally it's better to change an object's attributes through methods so that if you decide to rename size to hugeness you can do so on the variable while leaving getSize() and setSize() intact (so you don't have to change your code everywhere just in the Dog class = encapsulation).
Tony's suggestion of the dog subclasses is a great one to try too. If it doesn't make sense yet, come back to it after you read the chapter on polymorphism.
Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
Try implementing more methods, and then see what would be suitable.
If you have just this code, then it's fine.
But it would be interesting if you make more methods and data fields and see what more things you can do.
And in that case, go with what Tony has suggested.
Once you've done that, you can go further by making a mammal class and try dog and cat class extending it.
And then do more stuffs.
posted 4 years ago
Thanks for the ideas guys.
I will read up on polymorphism and attempt to add more methods.