Amazon Interview Question
How it helps: Circle,Square, Rectangle all inherit from class shape. Shape itself have an abstract method area() but does not implements it. Circle , Square, Rectangle will each implement its own version of it.
So When I make an Array that stores objects of type Shape and loop through it , calling array[i].area(), the area() mehtod of the appropraite obejct (square, rectangle,triangle, etc )will be called automatically. THis is polymorphism
Well, you can achieve polymorphism in Java through both methods and classes, right? Is that what the interviewer meant by "basic structures"?
The concept of inheritance helping in polymorphism is simple. If you have a base class, then its subclass might override some of its methods.
Another way in which you can use polymorphism is to use a variable of the base class type to hold a reference to an instance of the derived class.
From Wikipedia: "feature that allows values of different data types to be handled using a uniform interface"
In my own words: ability to call different things the same name
In Java: Interface.
Sample: interface Paintable { void paint(); }
And not only Shapes, but also Cars, Dogs, Fruits, Artists...
Capability of an action/method to do different things depending on type of an object; also relates to method overloading / overriding
In Java: Capability of an action/method to do different things depending on type of an object; also relates to method overloading / overriding
From Wikipedia: "feature that allows values of different data types to be handled using a uniform interface"
Sample: interface Paintable { void paint(); }
And not only Shapes, but also Cars, Dogs, Fruits, Artists... everyone/everything can paint :)
I think answer should be tree. Question isnt clear though.
- anonymous January 18, 2011The whole concept of polymorphism in java runs around inheritance. If there is no inheritance then only maybe old kind of polymorphism like method overloading would be available.