Object-Oriented Programming – Unique Method Definitions in Same Class Objects

object-orientedprogramming-languages

I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical.

However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different values for their fields. The result would be objects constructed from the same class no longer exhibiting the exact same behavior.

If I'm not mistaken, you can do this JavaScript? Along with this question, I ask, why would someone want to do this?

Best Answer

Methods in most (class-based) OOP languages are fixed by type.

JavaScript is prototype-based, not class based and so you can override methods on a per-instances base because there is no hard distinction between "class" and object; in reality, a "class" in JavaScript is an object which is like a template for how the instances should work.

Any language which allows first-class functions, Scala, Java 8, C# (via delegates) etc, can act like you have per-instance method overrides; you would have to define a field with a function type and then override it in each instance.

Scala has another posibility; In Scala, you can create object singletons (using the object keyword instead of the class keyword), so you can extend your class and override the methods, resulting in a new instance of that base class with overrides.

Why would someone do this? There could be dozens of reasons. It might be that the behavior needs to me more tightly defined than using various field combinations would allow. It could also keep the code decoupled and organized better. In general however, I think these cases a rarer and there often is a more straightforward solution using field values.