What is the difference between Abstraction and Polymorphism


Imagine a fraction class:

class fraction:
    int denominator
    int numerator

Now two objects of that:

fraction(obj1): denominator=-1 numerator=-1
fraction(obj2): denominator=1  numerator=1

Both objects have the value 1: (1/1) == (-1)/(-1). You wouldn’t expect they behave any different to the outside. That’s abstraction. You abstract the data your object holds into a logical view, even tho behind the scenes, there are other things. Theoretically, you have got a equivalence relation, with different equivalence groups:

[1]=(1, 1), (-1, -1), (5, 5), ...
[2]=(2, 4), (-2, -4), ...

And there is a abstraction function that abstracts the internal details to the outside:

f((1, 1)) = [1]
f((-1, -1)) = [1]

It maps from concrete values to the abstract values of an object. You do that by writing for example a constructor mapping (-1, -1) to (1, 1) and by writing a equals function for your class.


Imagine a pen and two derived classes:

class pen:
    void draw(int x, int y)

class pen_thin extends pen:
    void draw(int x, int y) { color(x, y) = green; }

class pen_thick extends pen:
    void draw(int x, int y) { color(x, y) = green; 
                              color(x, y+1) = green; }
and two objects:

Both pens can draw. your general “pen” cannot draw itself. It’s just an interface to pen_thin, pen_thick and lots of other pens. You say: obj1.draw(1, 0); and whether obj1 is a thick or a thin pen doesn’t matter to you as a user, neither to the compiler at compile time. The call behaves polymorphic. It’s dynamic polymorphism (happens at runtime) and that’s what people usually mean. Static Polymorphism happens at compile time:

class colorizer:
    void colorize(shirt s)
    void colorize(pants p)

That’s called overloading. You call obj.colorize(something). If you call it with a shirt reference, it will call the version taking a shirt. And if you call it with a pant reference, it will call the pants version. The choice done here is at compile-time.

Leave a Comment