About Dalip Mahal

Dalip is a principal consultant at Accelerated Development and has worked his way through all aspects of software development. He started as a software engineer and worked his way through engineering and product management.

Polymorphism and Inheritance are Independent of Each Other

Flexible programs focus on polymorphism and not inheritance.  Some languages focus on static type checking (C++, Java, C#) which links the concepts and reduces polymorphic opportunities. Languages that separate the concepts can allow you to focus on polymorphism and create more robust code. JavaScript, Python, Ruby, and VB.NET do not have typed variables and defer type checking to runtime. Is the value of static type checking worth giving up the power of pure polymorphism at runtime?

Inheritance and polymorphism are independent but related entities – it is possible to have one without the other. If we use a language that requires variables to have a specific type (C++, C#, Java)
 
then we might believe that these concepts are linked. If you only use languages that do not require variables to be declared with a specific type, i.e. var in JavaScript, def in Python, def in Ruby, dim in VB.NET then you probably have no idea what I’m squawking about! J

I believe that the benefits of pure polymorphism outweigh the value of static type checking. Now that we have fast processors, sophisticated debuggers, and runtime exception constructs the value of type checking at compile time is minimal. Some struggle with polymorphism, so let’s define it:

Polymorphism is the ability to send a message to an object without knowing what its type is.

Polymorphism is the reason why we can drive each others cars and why we can use different light switches. A car is polymorphic because you can send commonly understood messages to ANY car (start(), accelerate(), turnLeft(), turnRight(), etc) without knowing WHO built the car. A light switch is polymorphic because you can send the message turnOn() and turnOff() to any light switch without knowing who manufactured it.

Polymorphism is literally what makes our economy work. It allows us to build functionally equivalent products that can have radically different implementations. This is the basis for price and quality differences in products, i.e. toasters, blenders, etc.

Polymorphism through Inheritance

The UML diagram above shows how polymorphism is stated in languages like C++, Java, and C#. The method (a.k.a operation) start() is declared to be abstract (in UML), which defers the  implementation of the method to the subclasses in your target language. The method for start() is declared in class Car and specifies only the method signature and not an implementation (technically polymorphism requires that no code exists for method start() in class Car).

The code for method start() is then implemented separately in the VolkswagenBeetle and SportsCar subclasses. Polymorphism implies that start() is implemented using different  attributes in the subclasses, otherwise the start() method could simply been implemented in the super class Car. Even though most of us no longer code in C++, it is instructive to see why a strong link between inheritance and polymorphism kills flexibility.

 // C++ polymorphism through inheritance

class Car {
// declare signature as pure virtual function
     public virtual boolean start() = 0; 
}

class VolkswagenBeetle : Car {
     public boolean start() {
          // implementation code
}
}

class SportsCar : Car {
     public boolean start() {
          // implementation code
}
}

// Invocation of polymorphism
Car cars[] = { new VolkswagenBeetle(), new SportsCar() };

for( I = 0; I < 2; i++)
     Cars[i].start();

The cars array is of type Car and can only hold objects that derive from Car ( VolkswagenBeetle and SportsCar) and polymorphism works as expected. However, suppose I had the following additional class in my C++ program:

 // C++ lack of polymorphism with no inheritance


class Jalopy {
     public boolean start() {
          …
}
}

// Jalopy does not inherit from Car, the following is illegal

Car cars[] = { new VolkswagenBeetle(),new Jalopy() };

for( I = 0; I < 2; i++)
     Cars[i].start();

At compile time this will generate an error because the Jalopy type is not derived from Car. Even though they both implement the start() method with an identical signature, the compiler will stop me because there is a static type error. Strong type checking imposed at compile time means that all polymorphism has to come through inheritance. This leads to problems with deep inheritance hierarchies and multiple inheritance where there are all kinds of problems with unexpected side effects. Even moderately complex programs become very hard to understand and maintain in C++.

Historical note: C++ was dominant until the mid 1990s simply because it was an object oriented solution that was NOT interpreted.  This meant that on the slow CPUs of the time it had decent performance.  We used C++ because we could not get comparable performance with any of the interpreted object-oriented languages of the time, i.e. Smalltalk.

Weakening the Link

The negative effects of the tight link between inheritance and polymorphism lead both Java and C# to introduce the concept of interface to pry apart the ideas of inheritance and polymorphism but keep strong type checking at compile time. First it is possible to implement the above C++ example using inheritance as shown by the C# below:

 // C# polymorphism using inheritance

class Car {
     public virtual boolean start();  // declare signature
}

class VolkswagenBeetle : Car {
     public override boolean start() {
          // implementation code
}
}

class SportsCar : Car {
     public override boolean start() {
          // implementation code
}
}

// Invocation of polymorphism
Car cars[] = { new VolkswagenBeetle(), new SportsCar() };

for( I = 0; I < 2; i++)
     Cars[i].start();

In addition, through the use of the interface concept we can write the classes in Java as follows:

 // Java polymorphism using interface

interface Car {
     public boolean start(); 
}

class VolkswagenBeetle implements Car {
     public boolean start() {
          // implementation code
}
}

class SportsCar implements Car {
     public boolean start() {
          // implementation code
}
}

By using an interface, the implementations of the VolkswagenBeetle and SportsCar can be completely independent as long as they continue to satisfy the Car interface. In this manner, we can now get our Jalopy class to be polymorphic with the other two classes simply by:

 class Jalopy implements Car {
…
}

Polymorphism without Inheritance

There are languages where you have polymorphism without using inheritance. Some examples are JavaScript, Python, Ruby, VB.NET, and Small Talk. In each of these languages it is possible to write car.start() without knowing anything about the object car and its method.

 # Python polymorphism

class VolkswagenBeetle(Car):
     def start(): # Code to start Volkswagen

class SportsCar(Car):
     def start(): # Code to start SportsCar

# Invocation of polymorphism
cars = [ VolkswagenBeetle(), SportsCar() ]
for car in cars:
     car.start()

The ability to get pure polymorphism stems from these languages only have a single variable type prior to runtime i.e. var in JavaScript, def in Python, def in Ruby, dim in VB.NET. With only one variable type there can not be type error prior to runtime.

Historical note: It was only during the time frame when Java and C# were introduced that CPU power was sufficient for interpreted languages to give sufficient performance at run time.  The transition from having polymorphism and inheritance tightly coupled to being more loosely coupled depended on run time interpreters being able to execute practical applications with decent performance.

There is no Such Thing as a Free Lunch

When type checking is deferred to runtime you can end up with strange behaviors when you make method calls to objects that don’t implement the method, i.e. sending start() to an object with no start() method. When type checking is deferred to runtime you want an object to respond “I have no idea how to start()” if you send the start() method to it by accident.

Some pure polymorphic languages generally have a way of detecting missing methods:

  • In Visual Basic you can get the NotImplementedException
  • In Ruby you either implement the method_missing()  method or catch a NoMethodError exception
  • In Smalltalk you get the #doesNotUnderstand exception

Some languages don’t have exceptions but there are clunky work arounds:

  • In Python you have to use the getattr() call to see if an attribute exists for a name and then use callable() to figure out if it can be called.  For the car example above it would look like:
 startCar = getattr(obj, "start", None)
if callable(startCar):
    startCar ()
  • JavaScript (ECMAScript) will only raise an exception for a missing method in Firefox/Spidermonkey.

Even if you have a well defined exception mechanism (i.e. try catch), when you defer type checking to runtime it becomes harder to prove that your programs work correctly. Untyped variables at development time allow a developer to create collections of heterogeneous objects (i.e. sets, bags, vectors, maps, arrays). When you iterate over these heterogeneous collections there is always the possibility that a method will be called on an object that is not implemented. Even if you get an exception when this happens, it can take a long time for subtle problems to be found.

Conclusion


The concepts of polymorphism and inheritance are linked only if your language requires static type checking  (C++, Java, C#, etc). Any language with only a generic type for variable declaration has full separation of polymorphism and inheritance ( JavaScript, Python, Ruby, VB.NET), whether they are compiled to byte code or are directly interpreted. The original compiled languages (C++, etc) performed static type checking because of performance issues.
Performing type checking at compile time created a strong link between inheritance and polymorphism. Needing deep class inheritance structures and multiple inheritance lead to runtime side effects and code that was hard to understand.


Languages like C# and Java used the notion of an interface to preserve type checking at compile time to weaken the link between inheritance and polymorphism. In addition, these languages compile to a byte code that is interpreted at runtime to give a balance been static type checking and runtime performance.

Languages like Ruby, Python, JavaScript, Visual Basic, and Smalltalk take advantage of powerful CPUs to use interpreters to defer type checking to run time (whether the source code is compiled to byte code or purely interpreted). By deferring type checking we break the link between inheritance and polymorphism, however, this power comes with the difficulty of proving that a subtle runtime problem won’t emerge.

The one caveat to pure polymorphism is that we may develop subtle bugs that can be difficult to track down and fix. Pure polymorphism is only worth seeking if the language that you are using can reliably throw an exception when a method is not implemented.

Effective programmers are seeking polymorphism and not inheritance. The benefits of pure polymorphism outweigh any advantage that compile time type checking provides, especially when we have access to very sophisticated debuggers and support for runtime exception handling. In general, I believe that the benefits of pure polymorphism outweigh the value of static type checking.
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

8 Responses to "Polymorphism and Inheritance are Independent of Each Other"

  1. An article comparing Static vs. Dynamic typing and not a single mention of duck typing is a joke. Also, I have absolutely no idea why you seem to be implying variables are declaring using def in Python and Ruby, in both you simply do:
    name = value eg. answer = 42
    C# has had support for dynamic programming for quite some time http://msdn.microsoft.com/en-us/library/dd264736.aspx
    Lastly, the way the word polymorphism is thrown around in this article is really going to confuse people new to dynamic programming. A java example of polymorphism is:

    ClassName(Person person){
    //…Constructor
    }

    ClassName(Dog dog){
    //…Constructor
    }

    The compiler ensures only Persons and Object can be passed into the constructor thanks to strong typing. However, in Python, anything can be passed into a constructor (Weak typing). If there’s any validation to be done, it’s the programmer’s responsibility, but python will completely trust that if we call objectName.talk() that our object will have a talk method. I’d strongly suggest heavily editing this article to make these clearer. With the author’s use of def for python and ruby, I’d suggest they do some proper research and add some code samples too.
    You may also want to research duck punching, which is one of the more fascinating but dangerous parts of dynamic programming.

    • Mirko Friedenhagen says:

      Python is strongly but dynamically typed, compare 1 + “1” in Python which will throw a TypeError while in statically typed Java this will succeed and return “11” because Java automatically does a String.valueOf.

      • There is no such thing “strongly but dynamically typed”. What you are probably referring to is “Type Inference”, where a type is automatically assigned by the compiler/interpreter. While python does this (Which is why it’s considered weakly typed), it does not guarantee it during runtime. In Java a Bear object is a bear because that’s the type we gave it. That object can never become a Swan. The best we can do is create a new object and copy over bear’s attributes either through a method or manually using getters. In python, we can add and remove parts of an object during runtime as we please. If needed, we can use duck punching to give the Bear object wings so it can use the Fly method.
        As for your example of doing 1 + “1” in java, you’re right it won’t throw an exception. THAT IS BECAUSE IT WILL NOT COMPILE. Again, I’ll have to work under the assumption that you mean in a System.out.print(1 + “1”); statement. That is a completely different scenario and has nothing to do with static or dynamic typing, it’s simply a case of Java’s print casting everything to a string. What actually happens under the hood is a StringBuffer is created and each element is cast to a string then appended to the buffer. Python doesn’t do this because it introduces ambiguity. Part of the zen of python is to always choose explicit over implicit. For more reading on this I’d suggest this StackOverflow question. http://stackoverflow.com/questions/6380500/why-does-python-not-perform-type-conversion-when-concatenating-strings

    • Thomas, the article is not specifically about the different mechanisms that languages have for making polymorphism available. The point is that the benefits of polymorphism exceed any benefits being delivered from static inheritance.

  2. Mirko Friedenhagen says:

    In Python you get different errors when the method does not exist (AttributeError, TypeError or ValueError). However you are not able to easily differentiate between these:

    i = 1

    s = “a”

    In [11]: s / “a”

    —————————————————————————

    TypeError Traceback (most recent call last)

    in ()

    —-> 1 s / “a”

    TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’

    In [12]: len(i)

    —————————————————————————

    TypeError Traceback (most recent call last)

    in ()

    —-> 1 len(i)

    TypeError: object of type ‘int’ has no len()

    In [16]: s.foo()

    —————————————————————————

    AttributeError Traceback (most recent call last)

    in ()

    —-> 1 s.foo()

    AttributeError: ‘str’ object has no attribute ‘foo’

    In [17]: i.foo()

    —————————————————————————

    AttributeError Traceback (most recent call last)

    in ()

    —-> 1 i.foo()

    AttributeError: ‘int’ object has no attribute ‘foo’

  3. Prince William says:

    Excuse me for an offtop question, but what program was used to create a flowchart like this? Looks very useful. http://cdn.javacodegeeks.com/wp-content/uploads/2013/04/UMLPolymorphismNoInheritance.png

  4. Rob says:

    Interesting article! There is similar discussion here http://stackoverflow.com/q/24172820/684229 which basicly comes to the same conclusion.

    • Rob, actually I’m saying the exact opposite of the stackoverflow article. Many developers believe that polymorphism and inheritance are related simply because they only use languages where they are linked. My point is that they are not linked.

Leave a Reply


6 + four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close