I am a bit at beginner level in java. The following para is from head first java.
It was about how placing the methods(that are suitable for pets) in specific class(eg: dog,cat) instead of in parent class (eg:Animal) will make the programming difficult.
Two Big Problems with this approach. First off, you’d have to agree to a protocol, and all programmers of pet Animal classes now and in the future would have to KNOW about the protocol. By protocol, we mean the exact methods that we’ve decided all pets should have. The pet contract without anything to back it up. But what if one of the programmers gets it just a tiny bit wrong? Like, a method takes a String when it was supposed to take an int? Or they named it doFriendly() instead of beFriendly()? Since it isn’t in a contract, the compiler has no way to check you to see if you’ve implemented the methods correctly. Someone could easily come along to use the pet Animal classes and find that not all of them work quite right.
Here is a bit more specific question
First off, you’d have to agree to a protocol, and all programmers of pet Animal classes now and in the future would have to KNOW about the protocol
Why would i have to agree to a protocol and programmers of pet Animal classes now and in the future would have to KNOW about the protocol .
I believe suppose i write the pet methods in the dog class then i write it once whoever want to use the petmethod just call dogobject.petmethod(). What's with all those protocol.
Please tell us which page it is in HFJ. What is option 3? Can you see a similar problem with the following code?
posted 2 weeks ago
It's in page 221.
posted 2 weeks ago
Sierra and Bates Head First Java 2/e page 221.
It is not only programmers who have to know where the “pet” methods are, but the compiler. Not only would there be problems if somebody misspells one of the method names, but also there is no way for the compiler to know which Animal subclass has a beFriendly() method. What's more, it is entirely legal to write this sort of thing:-So what is going to happen if you know in advance that a is going to be a Dog, and what will happen in line 4 below?Because the compiler doesn't check whether there are any changes to the runtime type of the Animal reference, the only way it can “to thine own self be true” is to prohibit both beFriendly() calls. Goodbye line 2, goodbye line 4.
You need to read the whole chapter to find the correct solution.
God is a comedian playing for an audience that is afraid to laugh - Voltair. tiny ad:
Devious Experiments for a Truly Passive Greenhouse!