Howdy ranchers!
James wrote:
sorry, but thats (generics)in the next chapter.
You're right cowboy. Don't try to ride a wild mustang when you have problems with ponys.
What we are talking about here is called polymorphy and this is one of the key concepts of object oriented programming.
I modified Deepak's code a bit so it is now compiling:
In class Zoo the variable "animal" is of type Animal and can take any subtype of Animal as an object. Only not Animal itself because the class is abstract and cannot be instanciated. Hence no animal objects, only Animal type.
But in this code only at runtime (due to the random) it is clear, what kind of an animal the variable will hold.
The same is true for the array named "zoo". In the line "assing" an object of a subclass of Animal (thats is refered by the variable "animal") will taken as an element of the array.
And in the listening part you will also see polymorphy. Class animal demands a method makeSound from all non-abstract classes that extend Animal. It also has a non-abstract method (toString) that will be inherited by the subclasses.
Output is something like:
I am a Duck Quack
I am a Dog Bark
I am a Dog Bark
I am a Dog Bark
I am a Dog Bark
I am a Dog Bark
I am a Duck Quack
I am a Dog Bark
I am a Duck Quack
I am a Cat Meow
So having something like
Animal any = new Cat(); It is sure, that the object refered by variable
any surely has all methods, that are abstract in Animal in a concrete implementation.
An interface can be regarded as a special form of an abstract class that has no concrete (non-abstract) methods at all. But that would be a differend
thread.
See also:
How my dog learned polymorphism.
"anakindodoloveme anakindodoloveme" posted:
hehe , so funny !!
The Java Ranch follows a certain policy regarding user names.
The main reasons why and a link how to change yours you'll find here:
http://www.javaranch.com/name.jsp So, "anakindodoloveme anakindodoloveme" could you please change your user name before your next posting?
It will not affect anything you've already posted here. Just your user name will update.
Regards,
Bu.