简体   繁体   中英

Do we really need classes to implement polymorphism in Java?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM