In the method watchProgram
, all Java knows is that the argument is an InfoItem
. That argument may or may not be an Item
, and thus it may or may not have that method changeRecorded
. 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 method changeRecorded
doesn't exist in the argument item
.
Usually when you run into a situation like this, it's a sign that you shouldn't really be calling that changeRecorded
method 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 your watchProgram
method with some other implementation of InfoItem
that doesn't have a changeRecorded
method, what should watchProgram
do?
If, after some careful thought, you decide that it really is necessary for you to call the changeRecorded
method when the passed-in argument is an instance of Item
, you can use a cast to do so:
watchProgram(InfoItem item) {
// do stuff
if (item instanceof Item) { // thanks to ruslan for if statement
Item castedItem = (Item)item;
castedItem.changeRecorded();
}
// do stuff
}
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.