Coming from a C++ background, Im used to multiple inheritance. I like the feeling of a shotgun squarely aimed at my foot. Nowadays, I work more in C# and Java, where you can only inherit one baseclass but implement any number of interfaces (did I get the terminology right?).
For example, lets consider two classes that implement a common interface but different (yet required) baseclasses:
public class TypeA : CustomButtonUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
public class TypeB : CustomTextUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
Both classes are UserControls so I cant substitute the base class. Both needs to implement the DoMagic function. My problem now is that both implementations of the function are identical. And I hate copy-and-paste code.
The (possible) solutions:
I naturally want TypeA and TypeB to share a common baseclass, where I can write that identical function definition just once. However, due to having the limit of just one baseclass, I cant find a place along the hierarchy where it fits.
One could also try to implement a sort of composite pattern. Putting the DoMagic function in a separate helper class, but the function here needs (and modifies) quite a lot of internal variables/fields. Sending them all as (reference) parameters would just look bad.
My gut tells me that the adapter pattern could have a place here, some class to convert between the two when necessary. But it also feels hacky.
I tagged this with language-agnostic since it applies to all languages that use this one-baseclass-many-interfaces approach.
Also, please point out if I seem to have misunderstood any of the patterns I named.
In C++ I would just make a class with the private fields, that function implementation and put it in the inheritance list. Whats the proper approach in C#/Java and the like?
You can use the strategy pattern or something like it to use has a (composition) instead of is a (inheritance):
public class TypeA : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class TypeB : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class Magical : IMagician {
public void DoMagic() {
// shared magic
}
}
There are other ways to instantiate your private IMagician members (such as passing them as a param via constructor) but the above should get you started.
In .Net, you can have extension methods apply to interfaces. It's really neat when it's possible, and applicable for you because it's a rare way to apply a common implementation to an interface. Certainly consider it, but it might not work for you since you say that DoMagic works with a lot of Private members. Can you package these private variables internal possibly? This way the extension method could access them.
Have the common functionality in another class. If there's a logical place to put this common functionality, pass your objects to this other class method (perhaps this is UI functionality, and you already have a UI helper . . .). Again, can you expose the private data with an internal/public property? (Security/encapsulation is a concern in all this of course. I don't know if your classes are for internal use only or will be exposed publicly.)
Otherwise, pass a separate functionality class (or specific function pointer) into the interface-defined method. You would have to have a little bit of duplicated code to pass your private variables to this external function reference, but at least it wouldn't be much, and your implementation would be in one place.
We might be making this too complicated. It won't make you feel all object-oriented when you go to sleep tonight, but could you have a static routine in your library somewhere that all IMagician implementers call?
In the end, Adapter might indeed be what you're looking for. Less likely but still worth consideration is the Decorator pattern.
If nothing seems particularly good, pick what feel best, use it a couple times, and rearrange tomorrow. :)
Replace inheritance with composition.
Move your 'common' function to separate class, create an instance of that class, and insert it to TypeA object and to TypeB object.
Your gut is correct in this case. The Adapter pattern is what you're looking for.
DoFactory has good .NET examples (that should be pretty close to their Java counterparts as well):
Adapter Design Pattern in C# and VB.NET
The composite pattern is meant for complex objects, that means the focus is on one object being made up of other objects. The strategy-pattern can be regarded as a special case of that, but a strategy does not have to be an object. I think this would apply more to your case. Then again, this heavily depends on the nature of what DoMagic() does.
public interface IMagician{ /* declare here all the getter/setter methods that you need; they will be implemented both in TypeA and TypeB, right? */ }
public static class MyExtensions {
public static void doMagic(this IMagician obj)
{
// do your magic here
}
}
Now, the problem is if you REALLY need to use private properties/methods (as opposed to "internal" ones), this approach won't work. Well, actually, you may be able to do your magic if you can read those properties through reflection, but even if it works, it's a rather ugly solution :)
[Note that "doMagic" will automatically appear to become a part of TypeA and TypeB,simply because you implement IMagician - there is no need to have any implementation there ]
You can use composition to have magician as a property of typeA and typeB
class Magician : IMagician
{
public void DoMagic()
{}
}
Class TypeA : CustomButtonUserControl
{
//property
Magician magicianInTypeA
}
Class TypeB : CustomTextUserControl
{
//property
Magician magicianInTypeB
}
abstract class Magical: CustomButtonUserControl
{
public void DoMagic()
{
// ...
}
}
public class TypeA : Magical
{
}
public class TypeB : Magical
{
}
Related
I have some methods which their parameters are related to the fields, and have the same ids or similar ids.
Some programmming languages doesn't allow this, some do, which do you consider a "Best Practice" (for cross-language) ?
(The example is C++ alike, but apply to any progr. lang.)
Example:
public class AnyClass {
private string FilePath = "";
public void assignPath(string FilePath) { ... }; // <-- same as field member
public void assignPath(string AFilePath) { ... }; // <-- has a prefix
public void assignPath(string filePath) { ... }; // <-- different case
}
Cheers.
UPDATE: add "cross language"
One thing for sure. Don't use parameter names starting with capital letter. I haven't seen those as best practices in any language I know. Same for fields that are not public.
I like the third option in your example.
In general I believe "PascalCase" is used to denote static fields, and "camelCase" is used for instance fields. Also, as a general rule of thumb all method arguments should probably be "camelCase" or just "lower" if possible (I think a short truncation for a method argument is fine due to the limited scope).
However, I don't think having your method parameter arguments match exactly to instance field names is ideal in any situation. As far as prefixes go, any Hungarian notation should probably be avoided.
Here is a scenario in my mind and I have googled, Binged it a lot but got the answer like
"Abstract class has not implemented method so, we cant create the object"
"The word 'Abstract' instruct the compiler to not create an object of the class"
But in a simple class where we have all virtual method, able to create an object???
Also, we can define different access modified to Abstract class constructor like private, protected or public.
My search terminated to this question:
Why we can't create object of an Abstract class?
An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.
An abstract class has a protected constructor (by default) allowing derived types to initialize it.
For example, the base-type Stream is abstract. Without a derived type where would the data go? What would happen when you call an abstract method? There would be no actual implementation of the method to invoke.
Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.
Take for example an "Animal" abstract class. There's no such thing as a "pure" animal - there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn't be able to instantiate plain Animal - that's just a basic template. And there's certain functionality that all animals share, such as "makeSound()", but that can't be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?
It's intended to be used as a base class.
http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx
The abstract modifier can be used with
classes, methods, properties,
indexers, and events.
Use the abstract modifier in a class
declaration to indicate that a class
is intended only to be a base class of
other classes.
Abstract classes have the following
features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Abstract classes should have at least one virtual method or property that has no implementation. This is marked with the abstract keyword. Inheriting classes must provide an implementation if they are not abstract themselves. You cannot create an instance of an abstract class because it does not have a complete implementation. If it does, it should not be marked abstract in the first place.
As an addition to the other answers, you may not be able to create an instance of the abstract class, but you can certainly refer to instances of derived types through the abstract type and use methods or properties that are defined within the abstract base.
abstract class A
{
public abstract void D();
public void E() { }
}
class B : A
{
public override void D() { }
}
class C : A
{
public override void D() { }
}
...
A a = new B();
a.D();
a.E();
List<A> list = new List<A>() { new B(), new C() };
Simply speaking, an abstract class is like a shell of a class. Not all the methods have implementations, something like a circuit with some wire segments missing. While the majority of it may be constructed, it is up to the users to stick in the wires and resistors in those segments as they see fit.
As to why Java won't let you create it, part of it is just a failsafe (many abstract classes will function just fine without any additions as long as you don't call unimplemented methods).
If we have a class containing pure virtual function then the class is abstract. If we will create an object of the abstract class and calls the method having no body(as the method is pure virtual) it will give an error. That is why we cant create object of abstract class.
We cannot create object for abstract class bcoz ,mostly abstract class contain "abstract methods" ,so abstract methods are incomplete methods.so we cannot estimate the memory of those methods how much they are going to occupy .This is one of the reason why we cannot create object for abstract class.
Here is a similar StackOverflow question. In short, it is legal to have a public constructor on an abstract class. Some tools will warn you that this makes no sense.
Whats the utility of public constructors in abstract classes in C#?
Actually when we create an object of a normal class we use Constructor to allocate the memory
for that object like
myclass obj=new myclass();
Here using constructorr clr identifies how much memory the object needed depending upon the instance variabless and methods. But in case of abstract classes we cant predict the amount of memory required as we dont implement the abstract methods so its not possible to create object.
When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.
Source : Study Tonight
The reference studytonight :
When we create a pure virtual function in Abstract class, we reserve a
slot for a function in the VTABLE(studied in last topic), but doesn't
put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler
will not let the creation of object for such class and will display an
errror message whenever you try to do so.
Sorry guys...
You can Create object for an abstract class, if and only if that abstract class does not contains any abstract method.
Here is my Example. Copy it and compile and run.
abstract class Example {
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo {
public static void main(String[] args) {
Example ob = new Example(){};
ob.display();
}
}
So your answer is yes, we can create object for abstract class if it's no Abstract Method.
Check my program.
I don't agree with the accepted answer. The reason is that we can have body for pure virtual function.
The answer is that :
When we create a pure virtual function in the class, we reserve a slot for a function in the VTABLE, but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an error message whenever you try to do so.
we can create object for abstract class like this also...
public class HelloWorld
{
public static void main(String args[])
{
Person p = new Person()
{
void eat()
{
console.writeline("sooper..");
}
};
p.eat();
}
}
abstract class Person
{
abstract void eat();
}
every body is writing dat abstract class has some virtual function which has not defined. for dat reason we cant create object, but abstract class is a class with the key word 'abstract' which may or may not have abstract method. i think it is a concept, it does not take any memory for dat. so if we can create an object den a memory will be created which is not possible, for dat reason we can't create object of an abstract class bt we can create reference of it which does not occupy any memory location.
I am trying to create an ActionScript 3 class that implements two interfaces. The interfaces contain member functions with different signatures but the same name:
public interface IFoo
{
function doStuff(input:int):void;
}
public interface IBar
{
function doStuff(input1:String, input2:Number):void;
}
public class FooBar implements IFoo, IBar
{
// ???
}
In C# (for example) this is not a problem because methods can be overloaded, but ActionScript does not support overloading. Is there any way to create a class that implements both interfaces?
No, unfortunately this is not possible and it's because of the reason you already pointed out: ActionScript 3 does not support member overloading. It's a shame, but it's the unfortunate truth.
It is possible to have multiple members with the same name and even the same signature in a class, however, they must be qualified by namespace in that case. For instance, this should work:
public namespace foo;
public namespace bar;
foo function doStuf(input:int):void
{
// ...
}
bar function doStuff(input1:String, input2:String):void
{
// ...
}
You then reference the methods by qualifying them like so:
foo::doStuff(1);
bar::doStuff("foo", "bar");
Unfortunately, this won't help with your problem because even though the namespaces may be in the public namespace, they are still not the same as the public namespace itself meaning you're not satisfying the contract set forth by the interfaces (everything must be public). Making a long story short; unless you use some sort of composite pattern, you're out of luck until Adobe decides to implement member overloading.
public class FooBar would have to implement both interaces and thus implment those functions listed. Problem is ActionScript does not support method overloading. It is a nice feature that I miss from C# :(
I'm new to Windsor, but I'm certain there must be a way to do this...
I have a class with three different constructors:
public MyClass(string SomeParam)
{
...
}
public MyClass(string AnotherParam, string YetAnother)
{
...
}
public MyClass(string AnotherOne, string YeahIKnow, string AnnoyingExampleParam)
{
...
}
In my external configuration file, I have my service defined as:
<component
id="IMyClass"
service="IMyInterface, MyAssembly"
type="MyClass, MyOtherAssembly">
<parameters>
<AnotherOne>string value #1</AnotherOne>
<YeahIKnow>string value #2</YeahIKnow>
<AnnoyingExampleParam>string value #3</AnnoyingExampleParam>
</parameters>
</component>
When Windsor initializes an instance of my class, it only wants to initialize using the first (single string parameter) constuctor of my class, when I really want Windsor to use the third constructor.
I don't see anything in the docs about forcing the kernel to us a particular constructor using an external configuration, even though I can find references to doing it in code, but that sort of defeats the purpose of an external configuration!
Any advice would be appreciated.
Best,
David Montgomery
What version of Castle? I recall, from the depths of what goes for my memory at 4am in the morning, that there was a resolution for constructor work in Castle 2.0.
Humm, memory coming back a little now... Something tells me that Castle will construct the object with the first public ctor. May be as simple as moving what you want for Castle to load, to the top.
If that doesn't work for you, perhaps refactor your code a little?
Option 1) Make the first two constructors internal.
Option 2) Use a Factory pattern for your complex objects, which will utilize castle on the backend to new up the more simple or complex version.
Option 3) Create 3 classes from your base superclass, each having a more complicated constructor. This way, you can specific in the Castle config file exactly which service to load. For example:
public abstract class BaseClass
{
public BaseClass(String requiredParam)
{
...
}
}
public class SimpleClass : BaseClass
{
public SimpleClass(String requiredParam, String anotherParam)
: base(requiredParam)
{
...
}
}
public class MoreComplexClass : SimpleClass
{
public MoreComplexClass (String requiredParam, String anotherParam, String yetAnother)
: base(requiredParam, anotherParam)
{
...
}
}
But, I myself have not run into this yet. Mainly because I stick to only public 1 ctor on my classes, with a few private/internal ctors for things such as Linq to new up my objects with an empty ctor (since Linq doesn't support Dependency Injection, boo).
Note that in that last statement, internal ctors, that my SRP (Single Responsiblity Pattern) for resolving my IoC components is external, in a seperate higharchy assembly (i.e. an application or UI layer). Since it not internal to my domain objects, the internal ctors are not seen by Castle.
You must be doing something wrong.
Windsor uses the greediest constructor it can satisfy. If it uses the smaller one, you perhaps have some typo?
when your type is the service, you don't have to specify both
service="MyClass, MyAssembly"
type="MyClass">
remove the type.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can polymorphism be described in an easy-to-understand way?
We can find a lot of information about the subject on the Internet and books, like in Type polymorphism. But let's try to make it as simple as we can.
Two objects respond to the same message with different behaviors; the sender doesn't have to care.
Every Can with a simple pop lid opens the same way.
As a human, you know that you can Open() any such can you find.
When opened, not all cans behave the same way. Some contain nuts, some contain fake snakes that pop out. The result depends on what TYPE of can, if the can was a "CanOfNuts" or a "CanOfSnakes", but this has no bearing on HOW you open it. You just know that you may open any Can, and will get some sort of result that is decided based on what type of Can it was that you opened.
pUnlabledCan->Open(); //might give nuts, might give snakes. We don't know till we call it
Open() has a generic return type of "Contents" (or we might decide no return type), so that open always has the same function signature.
You, the human, are the user/caller.
Open() is the virtual/polymorphic function.
"Can" is the abstract base class.
CanOfNuts and CanOfSnakes are the polymorphic children of the "Can" class.
Every Can may be opened, but what specifically it does and what specific tye of contents it returns are defined by what sort of can it is.
All that you know when you see pUnlabledCan is that you may Open() it, and it will return the contents. Any other behaviors (such as popping snakes in your face) are decided by the specific Can.
This is from my answer from a similiar question. Here's an example of polymorphism in pseudo-C#/Java:
class Animal
{
abstract string MakeNoise ();
}
class Cat : Animal {
string MakeNoise () {
return "Meow";
}
}
class Dog : Animal {
string MakeNoise () {
return "Bark";
}
}
Main () {
Animal animal = Zoo.GetAnimal ();
Console.WriteLine (animal.MakeNoise ());
}
The Main() method doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.
The simplest description of polymorphism is that it is a way to reduce if/switch statements.
It also has the benefit of allowing you to extend your if/switch statements (or other people's ones) without modifying existing classes.
For example consider the Stream class in .NET. Without polymorphism it would be a single massive class where each method implements a switch statement something like:
public class Stream
{
public int Read(byte[] buffer, int offset, int count)
{
if (this.mode == "file")
{
// behave like a file stream
}
else if (this.mode == "network")
{
// behave like a network stream
}
else // etc.
}
}
Instead we allow the runtime to do the switching for us in a more efficient way, by automatically choosing the implementation based on the concrete type (FileStream, NetworkStream), e.g.
public class FileStream : Stream
{
public override int Read(byte[] buffer, int offset, int count)
{
// behave like a file stream
}
}
public class NetworkStream : Stream
{
public override int Read(byte[] buffer, int offset, int count)
{
// behave like a network stream
}
}
Poly: many
Morphism: forms / shapes
The Actor vs. the Character (or Role)
Apples and oranges are both fruit. Fruit can be eaten. Hence, both apples and oranges can be eaten.
The kicker? You eat them differently! You peel the oranges, but not the apples.
So the implementation differs, but the end result is the same, you eat the fruit.
If it walks like a duck and quacks like a duck, then you can treat it as a duck anywhere you need a duck.
This is a better article actually
Polymorphism allows Objects to "Look" the same, but behave in different ways. The usual example is to take an animal base class with a Speak() Method, A dog subclass would emit a Bark whereas a Pig subclass would emit an oink.
The 5 second short answer most people use so other developers can get their head around Polymorphism is overloading and overriding
Same syntax, different semantics.
Simplest way to describe it: a verb that can apply to more than one kind of object.
Everything else, as Hillel said, is just commentary.
Polymorphism is treating things abstractly by relying on knowledge of a common "parent" (think heirarchies like Animal as a parent of Dogs and Cats).
For example, all Animals can breathe oxygen, and while they may each do this differently you could design a facility that provides oxygen for Animals to breathe, supporting both Dogs and Cats.
As a little extra, you can do this even though Animal is an "abstract" identifier (there is no real "Animal" thing, just types of Animals).
Polymorphism is the storing of values of more than one type in a location of a single type.
Note that most of the other answers to this question, at the time of my writing, are actually describing dynamic dispatch, not polymorphism.
Dynamic dispatch requires polymorphism, but the reverse is not true. One could imagine a language very similar to Java or C# but whose System.Object had no members; typecasting would be necessary before doing anything with the value. In this notional language, there would be polymorphism, but not necessarily virtual methods, or any other dynamic dispatch mechanisms.
Dynamic dispatch is the related but distinct concept, well enough described in most of the other answers. However, the way it normally works in object-oriented languages (selecting a function based on the first ('this' or 'Self') argument type) is not the only way it can work. Multiple dispatch is also possible, where the selection is applied across the types of all the arguments.
Similarly, overload resolution and multiple dispatch are exact analogues of one another; overload resolution is multiple dispatch applied to static types, while multiple dispatch is overload resolution applied to runtime types stored in polymorphic locations.
Polymorphism is dividing the world into boxes based on common properties and treating the items in a given box as interchangeable when you only want to use these common properties.
Polymorphism is the ability to treat different things as if they were the same thing by establishing a shared identity between them then exploiting it.
Polymorphism is what you get when the same method applies to multiple classes. For example, both a String and a List might have "Reverse" methods. Both methods have the same name ("Reverse"). Both methods do something very similar (reverse all the characters or reverse the order of the elements in the list). But the implementation of each "Reverse" method is different and specific to its class. (In other words, the String reverses itself like a string, and the List reverses itself like a list.)
To use a metaphor, you could say "Make Dinner" to a French chef or to a Japanese chef. Each would perform "make dinner" in their own characteristic way.
The practical result is that you could create a "Reversing Engine" that accepts an object and calls "Reverse" on it. As long as the object has a Reverse method, your Reversing Engine will work.
To extend the chef analogy, you could build a "Waiterbot" that tells chefs to "Make Dinner". The Waiterbot doesn't have to know what type of dinner is going to be made. It doesn't even have to make sure it's talking to a chef. All that matters is that the "chef" (or fireman, or vending machine, or pet food dispenser) knows what to do when it's told to "Make Dinner".
What this buys you as a programmer is fewer lines of code and either type-safety or late binding. For example here's an example with type safety and early binding (in a c-like language that I'm making up as I go):
class BankAccount {
void SubtractMonthlyFee
}
class CheckingAccount : BankAccount {}
class SavingsAccount : BankAccount {}
AssessFee(BankAccount acct) {
// This will work for any class derived from
// BankAccount; even classes that don't exist yet
acct.SubtractMonthlyFee
}
main() {
CheckingAccount chkAcct;
SavingsAccount saveAcct;
// both lines will compile, because both accounts
// derive from "BankAccount". If you try to pass in
// an object that doesn't, it won't compile, EVEN
// if the object has a "SubtractMonthlyFee" method.
AssessFee(chkAcct);
AssessFee(saveAcct);
}
Here's an example with no type safety but with late binding:
class DatabaseConnection {
void ReleaseResources
}
class FileHandle {
void ReleaseResources
}
FreeMemory(Object obj) {
// This will work for any class that has a
// "ReleaseResources" method (assuming all
// classes are ultimately derived from Object.
obj.ReleaseResources
}
main() {
DatabaseConnection dbConn;
FileHandle fh;
// You can pass in anything at all and it will
// compile just fine. But if you pass in an
// object that doesn't have a "ReleaseResources"
// method you'll get a run-time error.
FreeMemory(dbConn);
FreeMemory(fh);
FreeMemory(acct); //FAIL! (but not until run-time)
}
For an excellent example, look at the .NET ToString() method. All classes have it because all classes are derived from the Object class. But each class can implement ToString() in a way that makes sense for itself.
EDIT: Simple != short, IMHO
Polymorphism is language functionality allowing high-level algorithmic code to operate unchanged on multiple types of data.
This is done by ensuring the operations invoke the right implementation for each data type. Even in an OOP context (as per this question's tag), this "right implementation" may be resolved at compile-time or run-time (if your language supports both). In some languages like C++, compiler-supplied support for run-time polymorphism (i.e. virtual dispatch) is specific to OOP, whereas other types of polymorphism can also operate on data types that aren't objects (i.e. not struct or class instances, but may be builtin types like int or double).
( The types of polymorphism C++ supports are listed and contrasted in my answer: Polymorphism in c++ - even if you program other languages, it's potentially instructive )
The way I try and think of it is something that looks the same but can have different functionality depending on the instance. So you can have a type
interface IJobLoader
but depending on how it is used can have different functionality while still looking the same. You may have instances for BatchJobLoader, NightlyJobLoader etc
Maybe I am way off.
The term polymorphism can also apply to overloading functions. For example,
string MyFunc(ClassA anA);
string MyFunc(ClassB aB);
is a non-object oriented example of polymorphism.
Is the ability that objects have to respond to the same message in different ways.
For instance , in languages such as smalltalk, Ruby, Objective-C, you just have to send the message and they will respond.
dao = XmlDao.createNewInstance() #obj 1
dao.save( data )
dao = RdbDao.createNewnewInstance() #obj 2
dao.save( data )
In this example two different objects, responded in different ways to the same messages: "createNewInstance() and save( obj )"
They act in different ways, to the same message. In the above languages, the classes might not even be in the same class hierarchy, it is enough that they respond to the message.
In languages such as Java, C++, C# etc. In order to assign the object to an object reference, they must share the same type hierarchy either by implementing the interface or by being subclass of a common class.
easy .. and simple.
Polymorphism is by far, the most important and relevant feature of object oriented programming.
It is a way to treat different things that can do something something similar in the same way without caring how they do it.
Let's say you have a game with a bunch of different types of Vehicles driving around such as Car, Truck, Skateboard, Airplane, etc... They all can Stop, but each Vehicle stops in a different way. Some Vehicles may need to shift down gears, and some may be able to come to a cold stop. Polymophism lets you do this
foreach (Vehicle v in Game.Vehicles)
{
v.Stop();
}
The way that stop is implemented is deferred to the different Vehicles so your program doesn't have to care about it.
It's just a way to get old cold to call new code. You write some application that accepts some "Shape" interface with methods that others must implement (example - getArea). If someone comes up with a new whiz-bang way to implement that interface your old code can call that new code via the the getArea method.
The ability of an object of some type (e.g. a car) to act (e.g. brake) like one of another type (e.g. a vehicle) which usually suggests common ancestry (e.g. car is a subtype of vehicle) at one point in the type hierarchy.
Polymorphism is the Object Oriented solution to problem of passing a function to another function. In C you can do
void h() { float x=3.0; printf("%f", x); }
void k() { int y=5; printf("%i", y); }
void g(void (*f)()) { f(); }
g(h); // output 3.0
g(k); // output 5
In C things get complicated if the function depends on additional parameters. If the functions h and k depend on different types of parameters you are in trouble and you must use casting. You have to store those parameters in a data structure, and pass a pointer to that data structure to g which passes it to h or k. h and k cast the pointer into a pointer to the proper structure and unpack the data. Very messy and very unsafe because of possible casting errors:
void h(void *a) { float* x=(float*)a; printf("%f",*x); }
void k(void *a) { int* y=(int*)a; printf("%i",*y); }
void g(void (*f)(void *a),void *a) { f(a); }
float x=3.0;
int y=5;
g(h,&x); // output x
g(k,&y); // output y
So they invented polymorphism. h and k are promoted to classes and the actual functions to methods, the parameters are member variables of the respective class, h or k. Instead of passing the function around, you pass an instance of the class that contains the function you want. The instance contains its own parameters.
class Base { virtual public void call()=0; }
class H : public Base { float x; public void call() { printf("%f",x);} } h;
class K : public Base { int y; public void call() { printf("%i",y);} } k;
void g(Base &f) { f.call(); };
h.x=3.0;
k.y=5;
g(h); // output h.x
g(k); // output k.x