1

While going through an answer on this site, I came across a line which says

Actually, you don't need classes for polymorphism at all

This comment was voted up. I know very well that

Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism. Method Overloading supports polymorphism because it is one way that Java implements one-interface, multiple methods paradigm.

I don't think other than through classes, we could have implemented polymorphism in Java. If it is not so, can someone elaborate with a nice example?

Alexis King
  • 43,109
  • 15
  • 131
  • 205
Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105
  • No you cannot implement it without the classes – Ashish Sep 27 '14 at 05:50
  • [This question](http://stackoverflow.com/questions/8355912/overloading-is-compile-time-polymorphism-really) has an answer that tries to distinguish "compile-time" from "run-time" polymorphism. It's interesting in a way. But when anybody talks about the importance of polymorphism in OOP, they're talking about run-time polymorphism only, because that's the kind of polymorphism that gives us all the advantages of reducing coupling, etc., that make OOP such a good idea. Overloading does not give you that. – ajb Sep 27 '14 at 06:09

1 Answers1

3

Polymorphism is simply the ability for many (poly) things to take the same form or shape (morph). The term itself is explained in more depth in this answer.

In C++, for example, this can be done quite easily without classes:

long getNum (int x)  { return x + 1; }
long getNum (long x) { return x - 1; }

Do that and you'll get quite different results with the two lines:

long x = getNum (1);
long y = getNum (1L);

You can do exactly the same thing in Java with static methods, involving no classes at all, but it's a bit of a waste of the language:

public class Test {
    public static long getNum (int x)  { return x + 1; }
    public static long getNum (long x) { return x - 1; }
    public static void main(String[] args) {
        System.out.println (getNum (1));
        System.out.println (getNum (1L));
    }
}

The output of that is:

2
0

Now you'll notice that there is actually a class in that Java code I posted but that's not a requirement to do polymorphism, it's more a requirement of the Java language to have everything embedded in a class. If you subscribe to the view that that make polymorphism dependent on classes, it also means that things like variable assignment and incrementing i requires classes.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953