I seem to not understand two OOP concepts very well. Could you explain what abstraction and polymorphism are, preferably with real examples and
Abstraction and polymorphism are critical concepts by no means limited to OO. Adding to the confusion, the word 'abstraction' is used multiple ways. Here is a quick cheat sheet with one example:
Data abstraction means information hiding. Usually what is hidden is the representation of a data structure. Example: I implement sets, but I don't tell you whether a set is represented as a list, a balanced binary tree, or an unbalanced binary tree. Done right, I can change representation without breaking your code.
Polymorphism means reuse with different types. So with my set example you could create sets of Social Security numbers, sets of full names, or sets of fruitbats, all using the same code.
Obviously you can define a class which is both abstract and polymorphic.
Polymorphism is further confusing because there are two ways to implement polymorphism. In parametric polymorphism, you can reuse the set with values of any type, or maybe any type satisfying some constraint. The most obvious examples are C++ templates; if you write
class Set { ... }
Then T
is the type of objects contained in the set (the notation
indicates a so-called "type parameter", which is what makes it parametric polymorphism).
In subtype polymorphism, you can reuse sets only with objects whose types are subtypes of a particular type. For example, you might be able to make sets only of objects that offer a less-than-or-equal-to method. In a true object-oriented language like Smalltalk or Ruby, which offer so-called duck typing (us pointy-headed theorists sometimes call it behavioral subtyping), the presence of the method is good enough. In a language like Java or C++, which conflate subtyping with inheritance, your use of polymorphism may be restricted to subclasses of a particular class. (Java further confuses the issue by using one form of subtyping on classes and another on interfaces.)
Finally, old farts like me talk about procedural abstraction, which just means being able to take a bunch of statements that are frequently used together and plop them into a procedure or method which you can then reuse. It's probably not germane to your question.
So, do you feel better about being confused?