This week's book giveaways are in the Jython/Python and Object-Oriented programming forums. We're giving away four copies each of Machine Learning for Business: Using Amazon SageMaker and Jupyter and Object Design Style Guide and have the authors on-line! See this thread and this one for details.
Gerard Charles wrote:. . . Do ya'll prefer . . . or . . .
No. I don't prefer either. One you start using instanceof (except when overriding the equals() method), I start getting suspicious about your use of inheritance. What you are doing is adding a method which isn't in the superclass; I think that is called functional extension as opposed to type extension, but I am not sure. It means your Dog class has a bark() method which isn't in the superclass. Can you hold you hand on your heart and say both of the following?
1: A dog is an animal.
2: A Dog object is an Animal object.
Does your Animal have a makeNoise() method or similar? Can you override it like this?Or like this?If you really can't get away without writing a bark() method, I would probably write the second form, but you might be able to use javap −c Dog to view the bytecode, and find that there isn't any difference betwen the two forms after they have been compiled.
Actually the developers of Java seem to have had some strong opinions on this matter, since they produced a proposal named JEP 305: Pattern Matching for instanceof. And if I read that proposal correctly it's already released in Java 14.