Forums Register Login

Why i can't access to te interface method?

+Pie Number of slices to send: Send
Hello
I'm a new programmer in JAVA. And i need to understand the "interfaces" with (real examples).
Let me to explain it:
This is an abstract class for polymorphism for the Animals (Dogs, Cats etc...):

This is an interface just for them (Tame) Animals.

I need to implements the Tame interface to the "Dog". As you know dog is a tame animal.

I have another class is for the Lion. Lion is not a Lame.

My problem is:
I can't access to the "Dog" (interface) via the polymorphism with this code:

IS NOT WORKING!!
But i can't access to it via the interface:

* Why i can't access to the "play" method via Animal?
* We know the interface is 100% abstract. If so why i can create a conrete class of it?
Thanks a lot
+Pie Number of slices to send: Send
"IS NOT WORKING!! " doesn't really tell us much of anything. Does it compile? does it run and error out? does it run, but not give you the output you are expecting?

So without knowing exactly what is happening, folks here probably can't give you much advice (or won't take the time to figure out what you mean).
+Pie Number of slices to send: Send
It has nothing to do with interfaces. Animal does not have a play() method. So when you have a reference to Animal, the compiler will not allow to access any method it does not possess.

The fact that the instance is really a Dog is moot; to access methods that are specific to Dog you'd need to declare or cast the reference to Dog.
+Pie Number of slices to send: Send
And yes, heed fred's advice. And I'd advise against posting in red and all uppercase. It's just annoying.
+Pie Number of slices to send: Send
IS NOT WORKING:
It says:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method play() is undefined for the type Animal

at myClass.main(myClass.java:35)
I want to know how can i access to the play with (polymorphism)?
+Pie Number of slices to send: Send


In this code you are trying to call the play method from an animal, which does not have access to the play() method. As mentioned before, even though you know it is a dog, and everyone else that reads the code knows it is a dog, to the system it is just an animal.

You could switch your array to something like Dog[] anm = new Dog[2], which would allow you to access play().
Put the moon back where you found it! We need it for tides and poetry and stuff. Like this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1176 times.
Similar Threads
a question about polymorphism ??
Arrays Doubt
Unable to understand reason for ClassCastException
Inheritance and Polymorphism
Casting to an Interface Type
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 07:23:40.