I have an assignment and i got a library including an interface class. [InfoItem]
I implement this class [Item].
Now i am required to write a method watchProgram(InfoItem item) [other class, importing InfoItem], which (as shown) requires an
InfoItem.
The passed parameter item has a variable ‘Recorded’ [boolean] which i want to edit using a method changeRecorded() that i defined in the implementation of InfoItem.
I cannot edit the interface and i get an error message that the method is not found [cannot find symbol]..
Any hints, suggestions, solutions?
Thanks!!
-Samuel-
In the method
watchProgram, all Java knows is that the argument is anInfoItem. That argument may or may not be anItem, and thus it may or may not have that methodchangeRecorded. Since Java can’t guarantee that the object has that method, it can’t insert the code to call the method when the class is compiled. As far as the Java compiler is concerned, the methodchangeRecordeddoesn’t exist in the argumentitem.Usually when you run into a situation like this, it’s a sign that you shouldn’t really be calling that
changeRecordedmethod in the first place. Think very carefully about why you think you need it and how you could change your own code to work without using it. For instance, if someone were to call yourwatchProgrammethod with some other implementation ofInfoItemthat doesn’t have achangeRecordedmethod, what shouldwatchProgramdo?If, after some careful thought, you decide that it really is necessary for you to call the
changeRecordedmethod when the passed-in argument is an instance ofItem, you can use a cast to do so:But as I said, this sort of thing should be used sparingly. The whole point of object-oriented programming (specifically, polymorphism) is to make it so you don’t have to do this.