View Single Post
Old 03-24-2006, 01:25 PM   #3 (permalink)
Belisarius
Java fanboy
 
Belisarius's Avatar
 
Join Date: Aug 2003
Posts: 1,174
Belisarius is on a distinguished road
Polymorphism is basically accessing a property of an object without knowing exactly what object that is. The most basic example in Java would be the "toString()" method implemented by all Objects. Take this code for instance (note, this isn't really legal Java code, it's just enough to illustrate the point):

Code:
// Define some example classes

class A {
  public String toString(){
    return "foo";
  }
}

class B {
  public String toString(){
    return "bar";
  }
}

// Define a method in some class

public void print(Object test){
  System.out.println(test);
}

// Put this in your main method

A a = new A();
B b = new B();

print(a);
Let's look at what is going on. First, look at the "print()" method. We told it to accept all objects of type "Object". Well, in Java, all objects are implicitly (that is they are by default) Objects in addition to their own types. That means A is an "Object" and B is and "Object". That also means that they can call all methods defined for "Object", one of which is "toString()".

Now, we wanted the "toString()" method to work differently in A than how it works in "Object" or B. So we "overrode" it, or rewrote it. This new "toString()" method only effects objects of type "A". Same goes for the "toString()" method defined in "B". But, because it was defined in the parent class "Object", Java knows it will *always* be defined. If we hadn't written a "toString()" method in "A" and "B", then it would have simply inheirited the "toString()" method written for "Object". Because Java knows that method will always be there, in our "print()" method, we can safely call it no matter what kind of "Object" we pass to it.

Now, you might be wondering how Java knows that the Object that we pass to "print()" is an A or B object, and which "toString()" method to call. Java keeps track of this all internally so you don't have to. If you tell a method to accept a certain object, it will accept not only that object, but all of its children (classes that inheirt/extend it) as well. However, only those methods and properties defined in the parent class (in this case, Object) will be accessible. That is, if we defined a "exampleMethod()" class in "A", in "print()" we could not say "test.exampleMethod()". We would have to "cast" the "test" object to "A", but that is outside the scope of this discussion.

To summarize, polymorphism (in Java at any rate) is the ability to access properties of a given object by calling on what is defined in the parent class without knowing exactly what the child class is.
__________________
GitS

Last edited by Belisarius; 03-25-2006 at 05:33 AM.
Belisarius is offline   Reply With Quote