tags:

views:

13277

answers:

14

In terms of Java, when someone says what is polymorphism. Would overloading or overriding be an acceptable answer?

I would seem to think that is a bit more than that. IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class is that still overridding?

I think overloading is not the right answer for sure.

+2  A: 

The term overloading refers to having multiple versions of something with the same name, usually methods with different parameter lists

public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }

So these functions might do the same thing but you have the option to call it with an ID, or a name. Has nothing to do with inheritance, abstract classes, etc.

Overriding usually refers to polymorphism, as you described in your question

Clyde
+6  A: 

You are correct that overloading is not the answer.

Neither is overriding. Overriding is the means by which you get polymorphism. Polymorphism is the ability for an object to vary behavior based on its type. This is best demonstrated when the caller of an object that exhibits polymorphism is unaware of what specific type the object is.

Alex B
It should not be the behaviour of the object that changes, but his implementation. Same behaviour, different implementation, that's polymorphism.
QBziZ
+1  A: 

overloading is when you define 2 methods with the same name but different parameters

overriding is where you change the behavior of the base class via a function with the same name in a subclass.

So Polymorphism is related to overriding but not really overloading.

However if someone gave me a simple answer of "overriding" for the question "What is polymorphism?" I would ask for further explanation.

Matt
+3  A: 

Polymorphism is the ability for an object to appear in multiple forms. This involves using inheritance and virtual functions to build a family of objects which can be interchanged. The base class contains the prototypes of the virtual functions, possibly unimplemented or with default implementations as the application dictates, and the various derived classes each implements them differently to affect different behaviors.

mxg
+3  A: 

The classic example, Dogs and cats are animals, animals have the method makeNoise. I can iterate through an array of animals calling makeNoise on them and expect that they would do there respective implementation.

The calling code does not have to know what specific animal they are.

Thats what I think of as polymorphism.

Brian G
+15  A: 

Here's an example of polymorphism in pseudo-C#/Java:

class Animal
{
    abstract string MakeNoise ();
}

class Cat : Animal {
    string MakeNoise () {
        return "Meow";
    }
}

class Dog : Animal {
    string MakeNoise () {
        return "Bark";
    }
}

Main () {
   Animal animal = Zoo.GetAnimal ();
   Console.WriteLine (animal.MakeNoise ());
}

The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.

Edit: Looks like Brian beat me to the punch. Funny we used the same example. But the above code should help clarify the concepts.

Mark A. Nicolosi
WE must have been in the same class.
Brian G
Yeah, this answer earned me the right to comment! I think the dog/cat example is way too common. I'me looking at my bookshelf and at least three books use it to describe polymorphism.
Mark A. Nicolosi
It's an example of runtime polymorphism. Compile time polymorphism is also possible through method overloading and generic types.
Pete Kirkham
Shape -> Parallelogram -> Rectangle -> Square
Mark
+1  A: 

Actually, both are used to achieve polymorphism.

  • You could have a method in a class that is overridden in one or more subclasses. The method does different things depending on which class was used to instantiate an object.

  • You could also have a method that it overloaded with two or more sets of arguments. The method does different things based on the type(s) of argument(s) passed.

Patrick McElhaney
Why was this voted down?
Patrick McElhaney
I suppose it was voted down because historically method overloading is not considered as part of polymorphism in the object oriented paradigm. Method overloading and polymorphism are two ortogonal, independent features of a programming language.
Sergio Acosta
As I stated in my answer here, I disagree -- the two features are not orthogonal, but are closely related. Polymorphism != Inheritance. You have my up-vote.
Peter Meyer
+1  A: 

Neither:

Overloading is when you have the same function name that takes different parameters.

Overriding is when a child class replaces a parent's method with one of its own (this in iteself does not constitute polymorphism).

Polymorphism is late binding, e.g. the base class (parent) methods are being called but not until runtime does the application know what the actual object is - it may be a child class whose methods are different. This is because any child class can be used where a base class is defined.

In Java you see polymorphism a lot with the collections library:

int countStuff(List stuff) {
  return stuff.size();
}

List is the base class, the compiler has no clue if you're counting a linked list, vector, array, or a custom list implementation, as long as it acts like a List:

List myStuff = new MyTotallyAwesomeList();
int result = countStuff(myStuff);

If you were overloading you'd have:

int countStuff(LinkedList stuff) {...}
int countStuff(ArrayList stuff) {...}
int countStuff(MyTotallyAwesomeList stuff) {...}
etc...

and the correct version of countStuff() would be picked by the compiler to match the parameters.

jpeacock
+1  A: 

Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)

anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:

class animal {
    public void makeRumor(){
        print("thump");
    }
}
class dog extends animal {
    public void makeRumor(){
        print("woff");
    }
}

animal a = new dog();
dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

(supposing that makeRumor is NOT virtual)

java doesn't truly offer this level of polymorphism (called also object slicing).

Lorenzo Boccaccia
some references: http://www.linuxtopia.org/online_books/programming_books/thinking_in_c++/Chapter15_017.html
Lorenzo Boccaccia
animal a = new dog();a was constructed as a dog, and will print "woff".If you want it to print thump then you need to upcast it.((animal) a).makeRumor()
chris
the upcast is done during the assignment
Lorenzo Boccaccia
That's reference upcasting, but the object is still a dog. If you want it to be an animal, you must explicitly upcast the object.
chris
Figured it out. Question was tagged Java. You answered C++. You may be correct in C++. I am definitely correct in Java.
chris
should happen every time a copy constructor is involvedhere is a reference http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.htmlcase three matches; ignore the new operator which is there only to disambiguate creation.
Lorenzo Boccaccia
found a comprehensive (and better) explanation, for further reading:http://bytes.com/forum/post2982201-3.html
Lorenzo Boccaccia
sorry for the flames, I was making this example in c++ (as per the post) as java doesn't truly support polymorphism so it's difficult to differentiate between the concepts in the question
Lorenzo Boccaccia
+9  A: 

Polymorphism is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.

An override is a type of function which occurs in a class which inherits from another class. An override function "replaces" a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. Referring to the previous example, you could define your own class and override the ToString() function. Because this function is inherited from Object, it will still be available if you copy an instance of this class into an Object-type variable. Normally, if you call ToString() on your class while it is pretending to be an Object, the version of ToString which will actually fire is the one defined on Object itself. However, because the function is an override, the definition of ToString() from your class is used even when the class instance's true type is hidden behind polymorphism.

Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism.

The Digital Gabeg
+4  A: 

Specifically saying overloading or overriding doesn't give the full picture. Polymorphism is simply the ability of an object to specialize its behavior based on its type.

I would disagree with some of the answers here in that overloading is a form of polymorphism (parametric polymorphism) in the case that a method with the same name can behave differently give different parameter types. A good example is operator overloading. You can define "+" to accept different types of parameters -- say strings or int's -- and based on those types, "+" will behave differently.

Polymorphism also includes inheritance and overriding methods, though they can be abstract or virtual in the base type. In terms of inheritance-based polymorphism, Java only supports single class inheritance limiting it polymorphic behavior to that of a single chain of base types. Java does support implementation of multiple interfaces which is yet another form of polymorphic behavior.

Peter Meyer
You're right in terms of what the words involved mean in general, but in a programming context, when people say "polymorphism" they always means "inheritance-based polymorphism". Interesting point, but I think that describing polymorphism this way will confuse people.
The Digital Gabeg
It may be easier to explain polymorphism in terms of inheritance alone, but the way this particular question was asked I think it's prudent to describe parametric polymorphism as well.
Patrick McElhaney
To be clear, I think the different forms should be stated -- which I haven't even adequately done -- because there are a few answers here that are presented as absolute. I respectfully disagree that in "programmer context ... 'polymorphism' always means 'inheritance-based polymorphism'"
Peter Meyer
+11  A: 

The clearest way to express polymorphism is via an abstract base class (0r interface)

public abstract class Human
{
   ...
   public abstract void goPee();
}

This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept -- You cannot create a human that is neither Male nor Female. It's got to be one or the other.

So we defer the implementation by using the abstract class.

public class Male extends Human
{
...
    public void goPee()
    {
        System.out.println("Stand Up");
    }
}

and

public class Female extends Human
{
...
    public void goPee()
    {
        System.out.println("Sit Down");
    }
}

Now we can tell an entire room full of Humans to go pee.

public static void main(String args)
{
    ArrayList<Human> group = new ArrayList<Human>();
    group.add(new Male());
    group.add(new Female());
    // ... add more...

    // tell the class to take a pee break
    for( Human person : group) person.goPee();
}

Running this would yield:

Stand Up
Sit Down
...
chris
This is an excelent example of polymorphism (in java) :) Great Answer!
unkiwii
Classic example.
codemeit
A: 

this is good ...

hussaintanzeel
A: 

Basically,polymorphism means is to take ability more than one form.Which means one interface and different method. overloading may occur when you define two method with the same name but different parameter. while overriding means when you wants to replace the behaviour of base class in to super class.

Ajit rajput.MCA.....