Use method not defined in Interface [Java]
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]开发者_如何学C, 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 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.
You may try next trick, that could be an option for you:
if (item instanceof Item) {
Item myItem = (Item) item;
myItem.changeRecorded();
}
Use this code inside of yours watchProgram() method.
Here we check whether parameter item is of type of Item class and if it's then convert to this type and call Item.changeRecorded() method.
if (item instanceof Item) {
((Item)item).changeRecorded();
}
However be aware that this is not good practice if it can be avoided. I would look to see if there is way to do what you want using only the methods defined in the interface, possibly by making the change a side effect of some other method.
If what you are doing is recording the fact that something has been done to InfoItem you might also consider recording the fact elsewhere than in the object.
精彩评论