What is polymorphism, what is it for, and how is it used?
If you think about the Greek roots of the term, it should become obvious.
Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
For example, in many languages, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.
But, in that same way, a class like BigDecimal or Rational or Imaginary can also provide those operations, even though they operate on different data types.
The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).
With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners and (possibly) a rotation. An irregular polygon needs a series of lines.
By making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw() function and the client code could simply do:
shape.Draw()
to get the correct behavior for any shape.
This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare() and drawCircle().
Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)
(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The monomer styrene happens to be made from carbon and hydrogen, C8H8, and polystyrene is made from groups of that, (C8H8)n.
Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.
Sometimes, you should just quit while you're behind :-)
Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.
Here is an example in C#. Create four classes within a console application:
public abstract class Vehicle
{
public abstract int Wheels;
}
public class Bicycle : Vehicle
{
public override int Wheels()
{
return 2;
}
}
public class Car : Vehicle
{
public override int Wheels()
{
return 4;
}
}
public class Truck : Vehicle
{
public override int Wheels()
{
return 18;
}
}
Now create the following in the Main() of the module for the console application:
public void Main()
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles.Add(new Bicycle());
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (Vehicle v in vehicles)
{
Console.WriteLine(
string.Format("A {0} has {1} wheels.",
v.GetType().Name, v.Wheels));
}
}
In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.
We then add a Bicycle, Car and Truck to the list.
Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.
This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.
I hope that this helps you.
From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.
Polymorphism is a long word for a very simple concept.
Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.
A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.
In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.
If anybody says CUT to these people
The Surgeon
The Hair Stylist
The Actor
What will happen?
The Surgeon would begin to make an incision.
The Hair Stylist would begin to cut someone's hair.
The Actor would abruptly stop acting out of the current scene,
awaiting directorial guidance.
So above representation shows What is polymorphism (same name, different behavior) in OOP.
If you are going for an interview and interviewer asks you tell/show a live example for polymorphism in the same room we are sitting at, say-
Answer - Door / Windows
Wondering How?
Through Door / Window - a person can come, air can come, light can come, rain can come, etc.
To understand it better and in a simple manner I used above example..
If you need reference for code follow above answers.
Simple Explanation by analogy
The President of the United States employs polymorphism. How? Well, he has many advisers:
Military Advisers
Legal Advisers
Nuclear physicists (as advisers)
etc etc.
Everyone Should only be responsible for one thing: Example:
The president is not an expert in zinc coating, or quantum physics. He doesn't know many things. But he does know how to run the country.
It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. This makes it easier to maintain code, especially if when you are making changes. Changes are inevitable. When things do change, you do not want to break other parts of your application. Presidents should stick to running the country, rather than getting into the nitty-gritty of specialist areas:
Why is that a bad idea for a president to know all those specific things?
If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.
For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.
Is there a better approach?
There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.
He can use a polymorphic approach to running the country.
Example - of using a polymorphic approach:
All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:
public class MisterPresident
{
public void RunTheCountry()
{
// assume the Petraeus and Condi classes etc are instantiated.
petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
condolezza.Advise(); // # she says negotiate trade deal with Iran
healthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
}
}
This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".
What you DON"T want:
public class MisterPresident
{
public void RunTheCountry()
{
// people walk into the Presidents office and he tells them what to do
// depending on who they are.
// Fallujah Advice - Mr Prez tells his military exactly what to do.
petraeus.IncreaseTroopNumbers();
petraeus.ImproveSecurity();
petraeus.PayContractors();
// Condi diplomacy advice - Prez tells Condi how to negotiate
condi.StallNegotiations();
condi.LowBallFigure();
condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();
// Health care
healthOfficial.IncreasePremiums();
healthOfficial.AddPreexistingConditions();
}
}
NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.
This allows the president to do what he does best: set general policy, look good and play golf :P.
How is it actually implemented - through a base class or a common interface
That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)
In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.
This would be ideal
public class MisterPresident
{
// You can pass in any advisor: Condi, HealthOfficials,
// Petraeus etc. The president has no idea who it will
// be. But he does know that he can ask them to "advise"
// and that's all Mr Prez cares for.
public void RunTheCountry(IAdvisor governmentOfficer)
{
governmentOfficer.Advise();
}
}
public class USA
{
MisterPresident president;
public USA(MisterPresident president)
{
this.president = president;
}
public void ImplementPolicy()
{
IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
president.RunTheCountry(governmentOfficer);
}
}
Summary
All that you really need to know is this:
The president doesn't need to know the specifics - those are left to others.
All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )
I really hope it helps you. If you don't understand anything post a comment and i'll try again.
Polymorphism is the ability to treat a class of object as if it is the parent class.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;
Polymorphism:
It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.
Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:
Just as the fields of a C structure are in a protected namespace, so
are an object’s instance variables.
Method names are also protected. Unlike the names of C functions,
method names aren’t global symbols. The name of a method in one
class can’t conflict with method names in other classes; two
very different classes can implement identically named methods.
Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.
The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.
Examples:
Example-1: Here is a simple example written in Python 2.x.
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.
Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.
But each have their own advanced features and more advanced technology involved in their move behavior.
Now let us create a basic type Car
Car.java
public class Car {
int price;
String name;
String color;
public void move(){
System.out.println("Basic Car move");
}
}
Let us implement the Ford Car example.
Ford extends the type Car to inherit all its members(properties and methods).
Ford.java
public class Ford extends Car{
public void move(){
System.out.println("Moving with V engine");
}
}
The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.
Honda.java
public class Honda extends Car{
public void move(){
System.out.println("Move with i-VTEC engine");
}
}
Just like Ford, Honda also extends the Car type and implemented the move method in its own way.
Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.
PolymorphismExample.java
public class PolymorphismExample {
public static void main(String[] args) {
Car car = new Car();
Car f = new Ford();
Car h = new Honda();
car.move();
f.move();
h.move();
}
}
Polymorphism Example Output:
In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.
Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.
So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.
But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.
So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.
Usually this refers the the ability for an object of type A to behave like an object of type B. In object oriented programming this is usually achieve by inheritance. Some wikipedia links to read more:
Polymorphism in object oriented programming
Type polymorphism
EDIT: fixed broken links.
Polymorphism is this:
class Cup {
int capacity
}
class TeaCup : Cup {
string flavour
}
class CoffeeCup : Cup {
string brand
}
Cup c = new CoffeeCup();
public int measure(Cup c) {
return c.capacity
}
you can pass just a Cup instead of a specific instance. This aids in generality because you don't have to provide a specific measure() instance per each cup type
I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:
Treating a derived type as if it were it's base type.
There are plenty of examples above that show this in action, but I feel this is a good concise answer.
(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )
http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife
read on from this part:
..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.
Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:
Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.
Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.
Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.
The term polymorphism comes from:
poly = many
morphism = the ability to change
In programming, polymorphism is a "technique" that lets you "look" at an object as being more than one type of thing. For instance:
A student object is also a person object. If you "look" (ie cast) at the student, you can probably ask for the student ID. You can't always do that with a person, right? (a person is not necessarily a student, thus might not have a student ID). However, a person probably has a name. A student does too.
Bottom line, "looking" at the same object from different "angles" can give you different "perspectives" (ie different properties or methods)
So this technique lets you build stuff that can be "looked" at from different angles.
Why do we use polymorphism? For starters ... abstraction. At this point it should be enough info :)
Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.
Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.
If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.
This is just an example of a possible design (in Java):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
I've provided a high-level overview of polymorphism for another question:
Polymorphism in c++
Hope it helps. An extract...
...it helps to start from a simple test for it and definition of [polymorphism]. Consider the code:
Type1 x;
Type2 y;
f(x);
f(y);
Here, f() is to perform some operation and is being given the values x and y as inputs. To be polymorphic, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.
( continued at Polymorphism in c++ )
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
Polymorphism is an ability of object which can be taken in many forms.
For example in human class a man can act in many forms when we talk about relationships.
EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:
public class PolymorphismExample {
public static abstract class Vehicle
{
public int wheels(){
return 0;
}
}
public static class Bike extends Vehicle
{
#Override
public int wheels()
{
return 2;
}
}
public static class Car extends Vehicle
{
#Override
public int wheels()
{
return 4;
}
}
public static class Truck extends Vehicle
{
#Override
public int wheels()
{
return 18;
}
}
public static void main(String[] args)
{
Vehicle bike = new Bike();
Vehicle car = new Car();
Vehicle truck = new Truck();
System.out.println("Bike has "+bike.wheels()+" wheels");
System.out.println("Car has "+car.wheels()+" wheels");
System.out.println("Truck has "+truck.wheels()+" wheels");
}
}
The result is:
For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.
Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:
// Class definitions
class Fraction
{
public $numerator;
public $denominator;
public function __construct($n, $d)
{
// In real life, you'd do some type checking, making sure $d != 0, etc.
$this->numerator = $n;
$this->denominator = $d;
}
public function display()
{
echo $this->numerator . '/' . $this->denominator;
}
}
class ComplexNumber
{
public $real;
public $imaginary;
public function __construct($a, $b)
{
$this->real = $a;
$this->imaginary = $b;
}
public function display()
{
echo $this->real . '+' . $this->imaginary . 'i';
}
}
// Main program
$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);
echo 'This is a fraction: '
$fraction->display();
echo "\n";
echo 'This is a complex number: '
$complex->display();
echo "\n";
Outputs:
This is a fraction: 1/2
This is a complex number: 1 + 2i
Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.
At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:
$userNumberChoice = $_GET['userNumberChoice'];
switch ($userNumberChoice) {
case 'fraction':
$userNumber = new Fraction(1, 2);
break;
case 'complex':
$userNumber = new ComplexNumber(1, 2);
break;
}
echo "The user's number is: ";
$userNumber->display();
echo "\n";
In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.
Polymorphism literally means, multiple shapes. (or many form) :
Object from different classes and same name method , but workflows are different.
A simple example would be:
Consider a person X.
He is only one person but he acts as many.
You may ask how:
He is a son to his mother.
A friend to his friends.
A brother to his sister.
Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.
for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well.
so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.
Polymorphism:
Different execution according to the instance of the class, not the type of reference variable.
An interface type reference variable can refer to any of the class instances that implement that interface.
What is polymorphism?
Polymorphism is the ability to:
Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type:
This is dynamic polymorphism.
Define several methods having the save name but having differents parameters:
This is static polymorphism.
The first if the historical definition and the most important.
What is polymorphism used for?
It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.
Strong and weak typing
Sample
Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.
public class Shape
{
public virtual void Draw()
{
DoNothing();
}
public virtual void Draw(int timeout)
{
DoNothing();
}
}
public class Point : Shape
{
int X, Y;
public override void Draw()
{
DrawThePoint();
}
}
public class Line : Point
{
int Xend, Yend;
public override Draw()
{
DrawTheLine();
}
}
public class Rectangle : Line
{
public override Draw()
{
DrawTheRectangle();
}
}
var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };
foreach ( var shape in shapes )
shape.Draw();
Here the Shape class and the Shape.Draw() methods should be marked as abstract.
They are not for to make understand.
Explaination
Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.
With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.
More readings
C# - Polymorphism (Level 1)
Polymorphism in Java (Level 2)
Polymorphism (C# Programming Guide)
Virtual method table
Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).
Do remember that each class must be saved in separate files.
The following code exemplifies Polymorphism:
The SuperClass:
public class Parent {
//Define things that all classes share
String maidenName;
String familyTree;
//Give the top class a default method
public void speak(){
System.out.println("We are all Parents");
}
}
The father, a subclass:
public class Father extends Parent{
//Can use maidenName and familyTree here
String name="Joe";
String called="dad";
//Give the top class a default method
public void speak(){
System.out.println("I am "+name+", the father.");
}
}
The child, another subclass:
public class Child extends Father {
//Can use maidenName, familyTree, called and name here
//Give the top class a default method
public void speak(){
System.out.println("Hi "+called+". What are we going to do today?");
}
}
The execution method, references Parent class to start:
public class Parenting{
public static void main(String[] args) {
Parent parents = new Parent();
Parent parent = new Father();
Parent child = new Child();
parents.speak();
parent.speak();
child.speak();
}
}
Note that each class needs to be declared in separate *.java files.
The code should compile.
Also notice that you can continually use maidenName and familyTree farther down.
That is the concept of polymorphism.
The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.
Hope this helps and makes it clear.
I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!
Polymorphism allows the same routine (function, method) to act on different types.
Since many existing answers are conflating subtyping with polymorphism, here are three ways (including subtyping) to implement polymorphism.
Parameteric (generic) polymorphism allows a routine to accept one or more type parameters, in addition to normal parameters, and runs itself on those types.
Subtype polymorphism allows a routine to act on any subtype of its parameters.
Ad hoc polymorphism generally uses routine overloading to grant polymorphic behavior, but can refer to other polymorphism implementations too.
See also:
http://wiki.c2.com/?CategoryPolymorphism
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++:
Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.
Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.
Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.
By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).
This is where I found the above definition. Around 50 minutes into the video the instructor explains the above.
https://www.youtube.com/watch?v=TMuno5RZNeE
First off all I believe that polymorphism is an essential part of object-oriented programming that enables us to define behavior shared by multiple classes but can be changed for each class separately. I would like share something from my experience in order to help in simple examples how to downsize complexity of code.
I can understand that in some ways it could be constructive for reusing code and keeping the maintainability part. It makes them less painful. But, like any other programming method, there are times when polymorphism might not be the best option.
Consider a base class called Car with a method called StartEngine() that tells the engine how to start. Suppose you have derived classes like MercedesBenzCar and TeslaModelSCar. In that case, you might be able to use polymorphism to define the StartEngine() method in the base Car class and then override that method in the derived classes to provide the specific implementation for each type of car. But this can get you into trouble. Let's review some code.
/// <summary>
/// Base class for car objects
/// </summary>
public abstract class Car
{
public virtual void StartEngine()
{
Console.WriteLine(value: "Car engine has been started.");
}
public virtual void StopEngine()
{
Console.WriteLine(value: "Car engine has been stopped.");
}
}
Once we have defined the base class, let's define derived classes.
/// <summary>
/// Example of polymorphism in C# using abstract classes on Mercedes Benz cars
/// </summary>
public class MercedesBenzCar : Car
{
public override void StartEngine()
{
Console.WriteLine(value: "Turning on the ignition and starting the Mercedes-Benz S Class...");
}
public override void StopEngine()
{
Console.WriteLine(value: "Turning off the ignition and stopping the Mercedes-Benz S Class...");
}
}
/// <summary>
/// Example of polymorphism in C# using abstract classes on Tesla Electric Cars
/// </summary>
public sealed class TeslaModelSCar : Car
{
public override void StartEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was activated...");
}
public override void StopEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was deactivated...");
}
}
So what's the point? In this example, the StartEngine() and StopEngine() methods of the base Car class show how to start and fundamentally start or stop a car. MercedesBenzCar and TeslaModelSCar classes override these methods to provide their implementations of the behavior unique to electric and fuel cars, respectively. So, it makes more sense to define the behavior directly in the derived classes instead of using polymorphism to describe it in the base class.
As you can see, this design might not be a good idea if the StartEngine() or StopEngine() methods behave very differently in each derived class. This is because it would take a lot of work to define a meaningful implementation of the StartEngine() or StopEngine() methods in the base class. In this case, it might be better to directly define the StartEngine() or StopEngine() method in the derived classes instead of using polymorphism.
How can we find a solution to this problem?
Let's look at this example again and see how inheritance and polymorphism can be used in C# when the behavior of the derived classes is very different.
Regarding refactoring, I'd like to suggest that interfaces or contracts be introduced as a potential resolution for this problem and give us a better design. Before we talk about interfaces, let's go over what they are. Inferences can be considered a proposal for a class or structure that describes they properties and methods.
A new version of C# could have a default implementations, but let's not make things harder than they need to be. If you want to learn more about it, check this link. In short, they say how the members signatures should look but not how implementation should look.
I would like to propose that the ICar interface defines two methods, StartEngine() and StopEngine(). The MercedesBenzCar and TeslaModelSCar classes should implement the ICar interface, which means that we can get rid of the abstract class here and convert it into an interface. So, Car should go to ICar.
Why? This can be a more flexible and sustainable design than inheritance because you can add or remove ICar interfaces from a class without affecting the class inheritance hierarchy. Let's now refactor our above solution to see it in practice.
/// <summary>
/// Base interface for all car types.
/// </summary>
public interface ICar
{
/// <summary>
/// Use this method to turn on the car engine.
/// </summary>
void StartEngine();
/// <summary>
/// Use this method to turn off the car engine.
/// </summary>
void StopEngine();
}
Once is interface ICar has been implemented, now is the time we refactor or concrete classes.
/// <summary>
/// Example of using the interface ICar for the class TeslaModelSCar.
/// </summary>
public sealed class TeslaModelSCar : ICar
{
public void StartEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was activated...");
}
public void StopEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was deactivated...");
}
}
/// <summary>
/// Example of using the interface ICar for the class MercedesBenzCar.
/// </summary>
public class MercedesBenzCar : ICar
{
public void StartEngine()
{
Console.WriteLine(value: "Turning on the ignition and starting the Mercedes-Benz S Class...");
}
public void StopEngine()
{
Console.WriteLine(value: "Turning off the ignition and stopping the Mercedes-Benz S Class...");
}
}
The refactoring process is now complete. It is now time to look at how to make use of it.
ICar teslaModelS = new TeslaModelSCar();
ICar mercedesBenz = new MercedesBenzCar();
teslaModelS.StartEngine();
mercedesBenz.StartEngine();
Console.WriteLine(value: "Press any key to stop engines...");
Console.ReadLine();
teslaModelS.StopEngine();
mercedesBenz.StopEngine();
await Task.Delay(delay: TimeSpan.FromSeconds(value: 3)); // Wait for 3 seconds in order to see the output
Imagine for a moment that we have a collection of cars in the garage and that there is another way to use it to start the cars engines in sequential order.
var carsInGarage = new ICar[2] { new TeslaModelSCar(), new MercedesBenzCar() };
foreach (var car in carsInGarage)
{
car.StartEngine();
}
Console.WriteLine(value: "Press any key to stop engines...");
Console.ReadLine();
foreach (var car in carsInGarage)
{
car.StopEngine();
}
await Task.Delay(delay: TimeSpan.FromSeconds(value: 3)); // Wait for 3 seconds in order to see the output
Again, polymorphism is a powerful object-oriented programming method that lets you define behavior shared by more than one class. But, like any other programming method, there are times when polymorphism might not be the best option. I believe that there are situation when we should consider the interface:
When a class's behavior is very different from that of its base
class. When there are a lot of classes that are based on it.
When performance is essential.
When you need to support more than one inheritance since C# doesn't do it by itself.
When deciding whether or not to use polymorphism in your code, I believe it's essential to keep these things in mind.
Cheers! 👋
Related
I am struggling with modeling a problem I have, for simplicity I have converted it to Birds example:
Let us say that we have birds, some can fly, some can't, however, all of them have wings, and all the flying birds fly exactly the same way.
My question is what is more suitable for the flying ability? usually, abilities are represented using interfaces, but that would require me to implement the Fly method inside each Bird although they fly the same way.
Another question would be, a bird needs wings to fly, what could represent a "Need-A" relationship? it would be a "Has-A" relationship from the Bird class perspective, but from the module representing the flying ability, it would be a "Need-A" relationship.
Here is my current class diagram.
To solve some of the above issues, I have converted the Bird to the abstract class which is inherited by CanFlyBird.
Is this the correct way to go?
Because seems like I still need to figure out how to pass the Wings of Bird Class to Fly method by default.
I have suggestion , you can take out CanFlyBird output of inheritance chain, and instead of that pass it via constructor , means make use of composition ,
so it will become
Bird get inherited to Eagle and Penguin , and you pass CanFlyBird as constructor argument to Eagle.
Code will be
interface IFly {
void fly();
}
and CanFlyBird will be
public class CanFlyBird : IFly {
public void Fly() {}
}
and Eagle will be
public class Eagle : Bird {
private readonly IFly _fly;
public Eagle (IFly fly) {
_fly = fly;
}
}
My suggestion is make use of Composition instead of going to loan chain of inheritance.
By this way if I want to make variation of canFlyBird class I can create it without changing my existing class
So it will become Bird has a flying capability
or if you want to follow current structure then
you can make fly method as virtual method in CanFlyBird class, so if someone wants to override it, that class can override else use base version
You're on the right track, but I think your second question is basically, "how do I make sure I can't construct a wingless bird".
The "Need-A" relationship is still a "Has-A" relationship. You have two ways to implement the requirement.
First, you can make a default value for your property in your Bird:
Wing wings = new Wing(); //as a field or
public Wing Wings { get; set; } = new Wing() //as a property
or second, and probably more correctly in this situation, require a Wing in your constructor:
public Bird(Wing wing) { this.wings = wing; }
As for "Fly()" I concur with others and recommend a virtual method. You can override this later in your subclasses, and if you decided one day to count swimming as flying, allow you to make minimal changes to the Penguin subclass to implement your change.
What is polymorphism, what is it for, and how is it used?
If you think about the Greek roots of the term, it should become obvious.
Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
For example, in many languages, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.
But, in that same way, a class like BigDecimal or Rational or Imaginary can also provide those operations, even though they operate on different data types.
The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).
With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners and (possibly) a rotation. An irregular polygon needs a series of lines.
By making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw() function and the client code could simply do:
shape.Draw()
to get the correct behavior for any shape.
This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare() and drawCircle().
Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)
(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The monomer styrene happens to be made from carbon and hydrogen, C8H8, and polystyrene is made from groups of that, (C8H8)n.
Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.
Sometimes, you should just quit while you're behind :-)
Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.
Here is an example in C#. Create four classes within a console application:
public abstract class Vehicle
{
public abstract int Wheels;
}
public class Bicycle : Vehicle
{
public override int Wheels()
{
return 2;
}
}
public class Car : Vehicle
{
public override int Wheels()
{
return 4;
}
}
public class Truck : Vehicle
{
public override int Wheels()
{
return 18;
}
}
Now create the following in the Main() of the module for the console application:
public void Main()
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles.Add(new Bicycle());
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (Vehicle v in vehicles)
{
Console.WriteLine(
string.Format("A {0} has {1} wheels.",
v.GetType().Name, v.Wheels));
}
}
In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.
We then add a Bicycle, Car and Truck to the list.
Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.
This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.
I hope that this helps you.
From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.
Polymorphism is a long word for a very simple concept.
Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.
A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.
In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.
If anybody says CUT to these people
The Surgeon
The Hair Stylist
The Actor
What will happen?
The Surgeon would begin to make an incision.
The Hair Stylist would begin to cut someone's hair.
The Actor would abruptly stop acting out of the current scene,
awaiting directorial guidance.
So above representation shows What is polymorphism (same name, different behavior) in OOP.
If you are going for an interview and interviewer asks you tell/show a live example for polymorphism in the same room we are sitting at, say-
Answer - Door / Windows
Wondering How?
Through Door / Window - a person can come, air can come, light can come, rain can come, etc.
To understand it better and in a simple manner I used above example..
If you need reference for code follow above answers.
Simple Explanation by analogy
The President of the United States employs polymorphism. How? Well, he has many advisers:
Military Advisers
Legal Advisers
Nuclear physicists (as advisers)
etc etc.
Everyone Should only be responsible for one thing: Example:
The president is not an expert in zinc coating, or quantum physics. He doesn't know many things. But he does know how to run the country.
It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. This makes it easier to maintain code, especially if when you are making changes. Changes are inevitable. When things do change, you do not want to break other parts of your application. Presidents should stick to running the country, rather than getting into the nitty-gritty of specialist areas:
Why is that a bad idea for a president to know all those specific things?
If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.
For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.
Is there a better approach?
There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.
He can use a polymorphic approach to running the country.
Example - of using a polymorphic approach:
All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:
public class MisterPresident
{
public void RunTheCountry()
{
// assume the Petraeus and Condi classes etc are instantiated.
petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
condolezza.Advise(); // # she says negotiate trade deal with Iran
healthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
}
}
This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".
What you DON"T want:
public class MisterPresident
{
public void RunTheCountry()
{
// people walk into the Presidents office and he tells them what to do
// depending on who they are.
// Fallujah Advice - Mr Prez tells his military exactly what to do.
petraeus.IncreaseTroopNumbers();
petraeus.ImproveSecurity();
petraeus.PayContractors();
// Condi diplomacy advice - Prez tells Condi how to negotiate
condi.StallNegotiations();
condi.LowBallFigure();
condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();
// Health care
healthOfficial.IncreasePremiums();
healthOfficial.AddPreexistingConditions();
}
}
NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.
This allows the president to do what he does best: set general policy, look good and play golf :P.
How is it actually implemented - through a base class or a common interface
That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)
In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.
This would be ideal
public class MisterPresident
{
// You can pass in any advisor: Condi, HealthOfficials,
// Petraeus etc. The president has no idea who it will
// be. But he does know that he can ask them to "advise"
// and that's all Mr Prez cares for.
public void RunTheCountry(IAdvisor governmentOfficer)
{
governmentOfficer.Advise();
}
}
public class USA
{
MisterPresident president;
public USA(MisterPresident president)
{
this.president = president;
}
public void ImplementPolicy()
{
IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
president.RunTheCountry(governmentOfficer);
}
}
Summary
All that you really need to know is this:
The president doesn't need to know the specifics - those are left to others.
All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )
I really hope it helps you. If you don't understand anything post a comment and i'll try again.
Polymorphism is the ability to treat a class of object as if it is the parent class.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;
Polymorphism:
It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.
Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:
Just as the fields of a C structure are in a protected namespace, so
are an object’s instance variables.
Method names are also protected. Unlike the names of C functions,
method names aren’t global symbols. The name of a method in one
class can’t conflict with method names in other classes; two
very different classes can implement identically named methods.
Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.
The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.
Examples:
Example-1: Here is a simple example written in Python 2.x.
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.
Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.
But each have their own advanced features and more advanced technology involved in their move behavior.
Now let us create a basic type Car
Car.java
public class Car {
int price;
String name;
String color;
public void move(){
System.out.println("Basic Car move");
}
}
Let us implement the Ford Car example.
Ford extends the type Car to inherit all its members(properties and methods).
Ford.java
public class Ford extends Car{
public void move(){
System.out.println("Moving with V engine");
}
}
The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.
Honda.java
public class Honda extends Car{
public void move(){
System.out.println("Move with i-VTEC engine");
}
}
Just like Ford, Honda also extends the Car type and implemented the move method in its own way.
Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.
PolymorphismExample.java
public class PolymorphismExample {
public static void main(String[] args) {
Car car = new Car();
Car f = new Ford();
Car h = new Honda();
car.move();
f.move();
h.move();
}
}
Polymorphism Example Output:
In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.
Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.
So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.
But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.
So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.
Usually this refers the the ability for an object of type A to behave like an object of type B. In object oriented programming this is usually achieve by inheritance. Some wikipedia links to read more:
Polymorphism in object oriented programming
Type polymorphism
EDIT: fixed broken links.
Polymorphism is this:
class Cup {
int capacity
}
class TeaCup : Cup {
string flavour
}
class CoffeeCup : Cup {
string brand
}
Cup c = new CoffeeCup();
public int measure(Cup c) {
return c.capacity
}
you can pass just a Cup instead of a specific instance. This aids in generality because you don't have to provide a specific measure() instance per each cup type
I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:
Treating a derived type as if it were it's base type.
There are plenty of examples above that show this in action, but I feel this is a good concise answer.
(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )
http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife
read on from this part:
..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.
Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:
Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.
Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.
Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.
The term polymorphism comes from:
poly = many
morphism = the ability to change
In programming, polymorphism is a "technique" that lets you "look" at an object as being more than one type of thing. For instance:
A student object is also a person object. If you "look" (ie cast) at the student, you can probably ask for the student ID. You can't always do that with a person, right? (a person is not necessarily a student, thus might not have a student ID). However, a person probably has a name. A student does too.
Bottom line, "looking" at the same object from different "angles" can give you different "perspectives" (ie different properties or methods)
So this technique lets you build stuff that can be "looked" at from different angles.
Why do we use polymorphism? For starters ... abstraction. At this point it should be enough info :)
Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.
Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.
If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.
This is just an example of a possible design (in Java):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
I've provided a high-level overview of polymorphism for another question:
Polymorphism in c++
Hope it helps. An extract...
...it helps to start from a simple test for it and definition of [polymorphism]. Consider the code:
Type1 x;
Type2 y;
f(x);
f(y);
Here, f() is to perform some operation and is being given the values x and y as inputs. To be polymorphic, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.
( continued at Polymorphism in c++ )
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
Polymorphism is an ability of object which can be taken in many forms.
For example in human class a man can act in many forms when we talk about relationships.
EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:
public class PolymorphismExample {
public static abstract class Vehicle
{
public int wheels(){
return 0;
}
}
public static class Bike extends Vehicle
{
#Override
public int wheels()
{
return 2;
}
}
public static class Car extends Vehicle
{
#Override
public int wheels()
{
return 4;
}
}
public static class Truck extends Vehicle
{
#Override
public int wheels()
{
return 18;
}
}
public static void main(String[] args)
{
Vehicle bike = new Bike();
Vehicle car = new Car();
Vehicle truck = new Truck();
System.out.println("Bike has "+bike.wheels()+" wheels");
System.out.println("Car has "+car.wheels()+" wheels");
System.out.println("Truck has "+truck.wheels()+" wheels");
}
}
The result is:
For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.
Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:
// Class definitions
class Fraction
{
public $numerator;
public $denominator;
public function __construct($n, $d)
{
// In real life, you'd do some type checking, making sure $d != 0, etc.
$this->numerator = $n;
$this->denominator = $d;
}
public function display()
{
echo $this->numerator . '/' . $this->denominator;
}
}
class ComplexNumber
{
public $real;
public $imaginary;
public function __construct($a, $b)
{
$this->real = $a;
$this->imaginary = $b;
}
public function display()
{
echo $this->real . '+' . $this->imaginary . 'i';
}
}
// Main program
$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);
echo 'This is a fraction: '
$fraction->display();
echo "\n";
echo 'This is a complex number: '
$complex->display();
echo "\n";
Outputs:
This is a fraction: 1/2
This is a complex number: 1 + 2i
Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.
At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:
$userNumberChoice = $_GET['userNumberChoice'];
switch ($userNumberChoice) {
case 'fraction':
$userNumber = new Fraction(1, 2);
break;
case 'complex':
$userNumber = new ComplexNumber(1, 2);
break;
}
echo "The user's number is: ";
$userNumber->display();
echo "\n";
In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.
Polymorphism literally means, multiple shapes. (or many form) :
Object from different classes and same name method , but workflows are different.
A simple example would be:
Consider a person X.
He is only one person but he acts as many.
You may ask how:
He is a son to his mother.
A friend to his friends.
A brother to his sister.
Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.
for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well.
so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.
Polymorphism:
Different execution according to the instance of the class, not the type of reference variable.
An interface type reference variable can refer to any of the class instances that implement that interface.
What is polymorphism?
Polymorphism is the ability to:
Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type:
This is dynamic polymorphism.
Define several methods having the save name but having differents parameters:
This is static polymorphism.
The first if the historical definition and the most important.
What is polymorphism used for?
It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.
Strong and weak typing
Sample
Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.
public class Shape
{
public virtual void Draw()
{
DoNothing();
}
public virtual void Draw(int timeout)
{
DoNothing();
}
}
public class Point : Shape
{
int X, Y;
public override void Draw()
{
DrawThePoint();
}
}
public class Line : Point
{
int Xend, Yend;
public override Draw()
{
DrawTheLine();
}
}
public class Rectangle : Line
{
public override Draw()
{
DrawTheRectangle();
}
}
var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };
foreach ( var shape in shapes )
shape.Draw();
Here the Shape class and the Shape.Draw() methods should be marked as abstract.
They are not for to make understand.
Explaination
Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.
With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.
More readings
C# - Polymorphism (Level 1)
Polymorphism in Java (Level 2)
Polymorphism (C# Programming Guide)
Virtual method table
Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).
Do remember that each class must be saved in separate files.
The following code exemplifies Polymorphism:
The SuperClass:
public class Parent {
//Define things that all classes share
String maidenName;
String familyTree;
//Give the top class a default method
public void speak(){
System.out.println("We are all Parents");
}
}
The father, a subclass:
public class Father extends Parent{
//Can use maidenName and familyTree here
String name="Joe";
String called="dad";
//Give the top class a default method
public void speak(){
System.out.println("I am "+name+", the father.");
}
}
The child, another subclass:
public class Child extends Father {
//Can use maidenName, familyTree, called and name here
//Give the top class a default method
public void speak(){
System.out.println("Hi "+called+". What are we going to do today?");
}
}
The execution method, references Parent class to start:
public class Parenting{
public static void main(String[] args) {
Parent parents = new Parent();
Parent parent = new Father();
Parent child = new Child();
parents.speak();
parent.speak();
child.speak();
}
}
Note that each class needs to be declared in separate *.java files.
The code should compile.
Also notice that you can continually use maidenName and familyTree farther down.
That is the concept of polymorphism.
The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.
Hope this helps and makes it clear.
I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!
Polymorphism allows the same routine (function, method) to act on different types.
Since many existing answers are conflating subtyping with polymorphism, here are three ways (including subtyping) to implement polymorphism.
Parameteric (generic) polymorphism allows a routine to accept one or more type parameters, in addition to normal parameters, and runs itself on those types.
Subtype polymorphism allows a routine to act on any subtype of its parameters.
Ad hoc polymorphism generally uses routine overloading to grant polymorphic behavior, but can refer to other polymorphism implementations too.
See also:
http://wiki.c2.com/?CategoryPolymorphism
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++:
Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.
Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.
Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.
By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).
This is where I found the above definition. Around 50 minutes into the video the instructor explains the above.
https://www.youtube.com/watch?v=TMuno5RZNeE
First off all I believe that polymorphism is an essential part of object-oriented programming that enables us to define behavior shared by multiple classes but can be changed for each class separately. I would like share something from my experience in order to help in simple examples how to downsize complexity of code.
I can understand that in some ways it could be constructive for reusing code and keeping the maintainability part. It makes them less painful. But, like any other programming method, there are times when polymorphism might not be the best option.
Consider a base class called Car with a method called StartEngine() that tells the engine how to start. Suppose you have derived classes like MercedesBenzCar and TeslaModelSCar. In that case, you might be able to use polymorphism to define the StartEngine() method in the base Car class and then override that method in the derived classes to provide the specific implementation for each type of car. But this can get you into trouble. Let's review some code.
/// <summary>
/// Base class for car objects
/// </summary>
public abstract class Car
{
public virtual void StartEngine()
{
Console.WriteLine(value: "Car engine has been started.");
}
public virtual void StopEngine()
{
Console.WriteLine(value: "Car engine has been stopped.");
}
}
Once we have defined the base class, let's define derived classes.
/// <summary>
/// Example of polymorphism in C# using abstract classes on Mercedes Benz cars
/// </summary>
public class MercedesBenzCar : Car
{
public override void StartEngine()
{
Console.WriteLine(value: "Turning on the ignition and starting the Mercedes-Benz S Class...");
}
public override void StopEngine()
{
Console.WriteLine(value: "Turning off the ignition and stopping the Mercedes-Benz S Class...");
}
}
/// <summary>
/// Example of polymorphism in C# using abstract classes on Tesla Electric Cars
/// </summary>
public sealed class TeslaModelSCar : Car
{
public override void StartEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was activated...");
}
public override void StopEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was deactivated...");
}
}
So what's the point? In this example, the StartEngine() and StopEngine() methods of the base Car class show how to start and fundamentally start or stop a car. MercedesBenzCar and TeslaModelSCar classes override these methods to provide their implementations of the behavior unique to electric and fuel cars, respectively. So, it makes more sense to define the behavior directly in the derived classes instead of using polymorphism to describe it in the base class.
As you can see, this design might not be a good idea if the StartEngine() or StopEngine() methods behave very differently in each derived class. This is because it would take a lot of work to define a meaningful implementation of the StartEngine() or StopEngine() methods in the base class. In this case, it might be better to directly define the StartEngine() or StopEngine() method in the derived classes instead of using polymorphism.
How can we find a solution to this problem?
Let's look at this example again and see how inheritance and polymorphism can be used in C# when the behavior of the derived classes is very different.
Regarding refactoring, I'd like to suggest that interfaces or contracts be introduced as a potential resolution for this problem and give us a better design. Before we talk about interfaces, let's go over what they are. Inferences can be considered a proposal for a class or structure that describes they properties and methods.
A new version of C# could have a default implementations, but let's not make things harder than they need to be. If you want to learn more about it, check this link. In short, they say how the members signatures should look but not how implementation should look.
I would like to propose that the ICar interface defines two methods, StartEngine() and StopEngine(). The MercedesBenzCar and TeslaModelSCar classes should implement the ICar interface, which means that we can get rid of the abstract class here and convert it into an interface. So, Car should go to ICar.
Why? This can be a more flexible and sustainable design than inheritance because you can add or remove ICar interfaces from a class without affecting the class inheritance hierarchy. Let's now refactor our above solution to see it in practice.
/// <summary>
/// Base interface for all car types.
/// </summary>
public interface ICar
{
/// <summary>
/// Use this method to turn on the car engine.
/// </summary>
void StartEngine();
/// <summary>
/// Use this method to turn off the car engine.
/// </summary>
void StopEngine();
}
Once is interface ICar has been implemented, now is the time we refactor or concrete classes.
/// <summary>
/// Example of using the interface ICar for the class TeslaModelSCar.
/// </summary>
public sealed class TeslaModelSCar : ICar
{
public void StartEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was activated...");
}
public void StopEngine()
{
Console.WriteLine(value: "The electric motor in the Tesla Model S car was deactivated...");
}
}
/// <summary>
/// Example of using the interface ICar for the class MercedesBenzCar.
/// </summary>
public class MercedesBenzCar : ICar
{
public void StartEngine()
{
Console.WriteLine(value: "Turning on the ignition and starting the Mercedes-Benz S Class...");
}
public void StopEngine()
{
Console.WriteLine(value: "Turning off the ignition and stopping the Mercedes-Benz S Class...");
}
}
The refactoring process is now complete. It is now time to look at how to make use of it.
ICar teslaModelS = new TeslaModelSCar();
ICar mercedesBenz = new MercedesBenzCar();
teslaModelS.StartEngine();
mercedesBenz.StartEngine();
Console.WriteLine(value: "Press any key to stop engines...");
Console.ReadLine();
teslaModelS.StopEngine();
mercedesBenz.StopEngine();
await Task.Delay(delay: TimeSpan.FromSeconds(value: 3)); // Wait for 3 seconds in order to see the output
Imagine for a moment that we have a collection of cars in the garage and that there is another way to use it to start the cars engines in sequential order.
var carsInGarage = new ICar[2] { new TeslaModelSCar(), new MercedesBenzCar() };
foreach (var car in carsInGarage)
{
car.StartEngine();
}
Console.WriteLine(value: "Press any key to stop engines...");
Console.ReadLine();
foreach (var car in carsInGarage)
{
car.StopEngine();
}
await Task.Delay(delay: TimeSpan.FromSeconds(value: 3)); // Wait for 3 seconds in order to see the output
Again, polymorphism is a powerful object-oriented programming method that lets you define behavior shared by more than one class. But, like any other programming method, there are times when polymorphism might not be the best option. I believe that there are situation when we should consider the interface:
When a class's behavior is very different from that of its base
class. When there are a lot of classes that are based on it.
When performance is essential.
When you need to support more than one inheritance since C# doesn't do it by itself.
When deciding whether or not to use polymorphism in your code, I believe it's essential to keep these things in mind.
Cheers! 👋
i've been doing some research on interfaces and a simple layman's explanation for what it truly is. when searching through seas of books For some reason people love using overly complex explanations and jargon to explain truly simple concepts (guess it makes them feel big) and i have a gut feeling it's the same in this case.
so from what i could grasp, it seems like interfaces are nothing more than a way to reserve method names, their return type if any, and the type and amount of arguments they accept. so when a class implements an interface (or interfaces) it is forced to define the body of each method from the interface(s). Am i on the nose with this one or do i need to keep digging?
p.s. i know javascript doesn't have support for interfaces, but i still need to understand the concept because there are quite a few places where it's shown how to emulate to an extent.
For some reason people love using overly complex explanations and jargon to explain truly simple concepts (guess it makes them feel big)
Consider eschewing the editorial comments that impute bad motives to people who are trying to help you. That's a really bad way to try to get people to help you.
It seems like interfaces are nothing more than a way to reserve method names, their return type if any, and the type and number of arguments they require. So when a class implements an interface (or interfaces) it is forced to define the body of each method from the interface(s). Am i on the nose with this one or do i need to keep digging?
You are on the right track but you err in the details. In C#, for example, an implementing class is not required to provide a body. The method which corresponds to the interface method could, for example, be an abstract method in an abstract class, which would then not have a body. And in C# an interface can require members other than methods; properties, events and indexers, for example.
A more concise and typical way to express the idea that interfaces impose a requirement that a type supply members that match certain signatures is to say that the interface represents a contract that must be fulfilled by its implementer. But that might be too complex and jargonish for your gut to stomach.
I explain the concept to lay people using an analogy that most people understand - plastic molding.
The interface defines the shape of an object in the exact same way a mold will provide the shape of the finished product.
You could inject a mold with White plastic, blue plastic, something exotic like an Epoxy or clay.
What matters is, no matter what they are actually made of, they all have the same exact consistent shape to the purchaser of the product.
For code, this means no matter what code is used to implement the interface, they all follow the same consistent contract/shape to the end user.
I hope that might help a little.
Edit -
To extend the analogy to Abstract classes, imagine the next step in the molding process. You run a White, blue, and red plastic production run, but then each item needs to be painted at a separate factory, we just ship them out.
The item is not finished, but it does have its shape defined. Someone later will come and fill out the details that our factory left blank.
These items cannot be sold until they get that last painting step.
In code, the abstract implementation of the interface provides some (or none) of the implementation, but leaves another descendant class to complete the contract, and in the same way no one can create an instance of the class until the contract has been completed.
In the same way though, you can still refer to an abstract class in code, just like you can refer to the unpainted mold item as a "White molded thing" wither or not it is painted!
Edit 2
Here's a short example
void Main()
{
//IMold mold = new IMold(); // error - can't create instance of an interface
//Fruit fruit = new Fruit(); // error - can't create instance of an abstract class
Apple apple1 = new Apple(); // good
Orange orange1 = new Orange(); // good
Fruit apple2 = (Fruit)apple1; // good - Apples are fruit
Fruit orange2 = (Fruit)orange1; // good - oranges are fruit
IFruitMold apple3 = (IFruitMold)apple2; // good - Apples fit the Mold
IFruitMold orange3 = (IFruitMold)orange2; // good - Oranges also fit the mold
//now I can do this:
//Notice that `fruits` is of type IList<T> but the new is List<T>
//This is the exact concept we are talking about
//IList<T> is some kind of set of items that can be added or subtracted from
//but we don't have to care about the implementation details of *HOW* this is done
IList<IFruitMold> fruits = new List<IFruitMold>();
fruits.add(apple3);
fruits.add(orange3);
foreach( var fruit in fruits )
{
fruit.PlasticColor.Dump(); // ok I can read
fruit.PlasticColor = ""; // error - no Set defined in the interface
// depending on the **implementation details** of what type of fruit this is true or false
// we don't care in the slightest, we just care that we have some IFruitMold instances
fruit.RequiresPainting.Dump();
}
}
interface IFruitMold
{
string PlasticColor { get; }
bool RequiresPainting { get; }
}
abstract class Fruit : IFruitMold
{
private string m_PlasticColor = string.Empty;
public string PlasticColor { get; private set; }
public abstract bool RequiresPainting { get; }
}
//notice that we only define the abstract portion of the base class
//it defined PlasticColor for us already!
//the keyword `override` is required - it is to make it clear that
//this member is overriding a member from it's parent.
class Apple : Fruit
{
public override bool RequiresPainting { get { return true; } }
}
class Orange : Fruit
{
public override bool RequiresPainting { get { return false; } }
}
Yes, in a nutshell interfaces are there to declare and promise everyone else that a class will have certain methods.
This is good when you create generalized methods and function, where you want a more abstract design. All you want to know is that your function can receive an object that had methods A B and C.
Interface is just a simple empty class, that show the contract on how you real class should look. I think you have the concept ok.
They don't reserve anything (I don't understand what you mean by that), is just a way so when you build your class around the interface, you have a prior knowledge of how will your class look like. And also you can know before which methods will it have.
when a class implements an interface (or interfaces) it is forced to define the body of each method from the interface(s).
Yes. Interfaces are contracts. They let others know that your class implements certain functionality.
I would say its more than reserving the method name it is a way of making a contract that the method will exist and the caller will not need to know what it does but it will still be available to be called
A good example would be a pen and pencil both can implement an Iwriter interface with a write method but whoever calls the write method doesn't need to know that one uses ink and one uses lead the caller will just know that it is going to write words on the paper.
Interfaces provide a uniform way of interaction with a set of objects.
No matter what the object is, if it implements the interface we know that it will respond to a method defined in the interface. In this way, we can create objects that represent different things in a project and still interact with them in the same way. The actual implementation of the methods defined in the interface can be completely different, but they will take the same inputs and provide the same type of output.
Basically an interface is a contract which can define properties (getters and setters) or methods (with whatever parameters you require). If an object 'implements' the interface it needs to define a concrete implementation for ALL the properties and methods defined in the interface.
For unit testing or Inversion of Control containers interfaces really come into there own as you can call methods/properties on the interface without knowing anything about the object which actually implements it.
Interface is used to provide common functionality among a set of completely unrelated objects.
Lets say we have a bunch of animal objects and we need to separate pets from that bunch. The task of separation becomes really simple if we enforce a contract such that all the animals which are pets needs to implement IPet interface.
The reason for interfaces truly eludes me. From what I understand, it is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# (or so I was told).
All I see is, you predefine some members and functions, which then have to be re-defined in the class again. Thus making the interface redundant. It just feels like syntactic… well, junk to me (Please no offense meant. Junk as in useless stuff).
In the example given below taken from a different C# interfaces thread on stack overflow, I would just create a base class called Pizza instead of an interface.
easy example (taken from a different stack overflow contribution)
public interface IPizza
{
public void Order();
}
public class PepperoniPizza : IPizza
{
public void Order()
{
//Order Pepperoni pizza
}
}
public class HawaiiPizza : IPizza
{
public void Order()
{
//Order HawaiiPizza
}
}
No one has really explained in plain terms how interfaces are useful, so I'm going to give it a shot (and steal an idea from Shamim's answer a bit).
Lets take the idea of a pizza ordering service. You can have multiple types of pizzas and a common action for each pizza is preparing the order in the system. Each pizza has to be prepared but each pizza is prepared differently. For example, when a stuffed crust pizza is ordered the system probably has to verify certain ingredients are available at the restaurant and set those aside that aren't needed for deep dish pizzas.
When writing this in code, technically you could just do
public class Pizza
{
public void Prepare(PizzaType tp)
{
switch (tp)
{
case PizzaType.StuffedCrust:
// prepare stuffed crust ingredients in system
break;
case PizzaType.DeepDish:
// prepare deep dish ingredients in system
break;
//.... etc.
}
}
}
However, deep dish pizzas (in C# terms) may require different properties to be set in the Prepare() method than stuffed crust, and thus you end up with a lot of optional properties, and the class doesn't scale well (what if you add new pizza types).
The proper way to solve this is to use interface. The interface declares that all Pizzas can be prepared, but each pizza can be prepared differently. So if you have the following interfaces:
public interface IPizza
{
void Prepare();
}
public class StuffedCrustPizza : IPizza
{
public void Prepare()
{
// Set settings in system for stuffed crust preparations
}
}
public class DeepDishPizza : IPizza
{
public void Prepare()
{
// Set settings in system for deep dish preparations
}
}
Now your order handling code does not need to know exactly what types of pizzas were ordered in order to handle the ingredients. It just has:
public PreparePizzas(IList<IPizza> pizzas)
{
foreach (IPizza pizza in pizzas)
pizza.Prepare();
}
Even though each type of pizza is prepared differently, this part of the code doesn't have to care what type of pizza we are dealing with, it just knows that it's being called for pizzas and therefore each call to Prepare will automatically prepare each pizza correctly based on its type, even if the collection has multiple types of pizzas.
The point is that the interface represents a contract. A set of public methods any implementing class has to have. Technically, the interface only governs syntax, i.e. what methods are there, what arguments they get and what they return. Usually they encapsulate semantics as well, although that only by documentation.
You can then have different implementations of an interface and swap them out at will. In your example, since every pizza instance is an IPizza you can use IPizza wherever you handle an instance of an unknown pizza type. Any instance whose type inherits from IPizza is guaranteed to be orderable, as it has an Order() method.
Python is not statically-typed, therefore types are kept and looked up at runtime. So you can try calling an Order() method on any object. The runtime is happy as long as the object has such a method and probably just shrugs and says »Meh.« if it doesn't. Not so in C#. The compiler is responsible for making the correct calls and if it just has some random object the compiler doesn't know yet whether the instance during runtime will have that method. From the compiler's point of view it's invalid since it cannot verify it. (You can do such things with reflection or the dynamic keyword, but that's going a bit far right now, I guess.)
Also note that an interface in the usual sense does not necessarily have to be a C# interface, it could be an abstract class as well or even a normal class (which can come in handy if all subclasses need to share some common code – in most cases, however, interface suffices).
For me, when starting out, the point to these only became clear when you stop looking at them as things to make your code easier/faster to write - this is not their purpose. They have a number of uses:
(This is going to lose the pizza analogy, as it's not very easy to visualise a use of this)
Say you are making a simple game on screen and It will have creatures with which you interact.
A: They can make your code easier to maintain in the future by introducing a loose coupling between your front end and your back end implementation.
You could write this to start with, as there are only going to be trolls:
// This is our back-end implementation of a troll
class Troll
{
void Walk(int distance)
{
//Implementation here
}
}
Front end:
function SpawnCreature()
{
Troll aTroll = new Troll();
aTroll.Walk(1);
}
Two weeks down the line, marketing decide you also need Orcs, as they read about them on twitter, so you would have to do something like:
class Orc
{
void Walk(int distance)
{
//Implementation (orcs are faster than trolls)
}
}
Front end:
void SpawnCreature(creatureType)
{
switch(creatureType)
{
case Orc:
Orc anOrc = new Orc();
anORc.Walk();
case Troll:
Troll aTroll = new Troll();
aTroll.Walk();
}
}
And you can see how this starts to get messy. You could use an interface here so that your front end would be written once and (here's the important bit) tested, and you can then plug in further back end items as required:
interface ICreature
{
void Walk(int distance)
}
public class Troll : ICreature
public class Orc : ICreature
//etc
Front end is then:
void SpawnCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
creature.Walk();
}
The front end now only cares about the interface ICreature - it's not bothered about the internal implementation of a troll or an orc, but only on the fact that they implement ICreature.
An important point to note when looking at this from this point of view is that you could also easily have used an abstract creature class, and from this perspective, this has the same effect.
And you could extract the creation out to a factory:
public class CreatureFactory {
public ICreature GetCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
return creature;
}
}
And our front end would then become:
CreatureFactory _factory;
void SpawnCreature(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
}
The front end now does not even have to have a reference to the library where Troll and Orc are implemented (providing the factory is in a separate library) - it need know nothing about them whatsoever.
B: Say you have functionality that only some creatures will have in your otherwise homogenous data structure, e.g.
interface ICanTurnToStone
{
void TurnToStone();
}
public class Troll: ICreature, ICanTurnToStone
Front end could then be:
void SpawnCreatureInSunlight(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
if (creature is ICanTurnToStone)
{
(ICanTurnToStone)creature.TurnToStone();
}
}
C: Usage for dependency injection
Most dependency injection frameworks work when there is a very loose coupling between the front end code and the back end implementation. If we take our factory example above and have our factory implement an interface:
public interface ICreatureFactory {
ICreature GetCreature(string creatureType);
}
Our front end could then have this injected (e.g an MVC API controller) through the constructor (typically):
public class CreatureController : Controller {
private readonly ICreatureFactory _factory;
public CreatureController(ICreatureFactory factory) {
_factory = factory;
}
public HttpResponseMessage TurnToStone(string creatureType) {
ICreature creature = _factory.GetCreature(creatureType);
creature.TurnToStone();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
With our DI framework (e.g. Ninject or Autofac), we can set them up so that at runtime a instance of CreatureFactory will be created whenever an ICreatureFactory is needed in an constructor - this makes our code nice and simple.
It also means that when we write a unit test for our controller, we can provide a mocked ICreatureFactory (e.g. if the concrete implementation required DB access, we don't want our unit tests dependent on that) and easily test the code in our controller.
D: There are other uses e.g. you have two projects A and B that for 'legacy' reasons are not well structured, and A has a reference to B.
You then find functionality in B that needs to call a method already in A. You can't do it using concrete implementations as you get a circular reference.
You can have an interface declared in B that the class in A then implements. Your method in B can be passed an instance of a class that implements the interface with no problem, even though the concrete object is of a type in A.
Examples above don't make much sense. You could accomplish all above examples using classes (abstract class if you want it to behave only as a contract):
public abstract class Food {
public abstract void Prepare();
}
public class Pizza : Food {
public override void Prepare() { /* Prepare pizza */ }
}
public class Burger : Food {
public override void Prepare() { /* Prepare Burger */ }
}
You get the same behavior as with interface. You can create a List<Food> and iterate that w/o knowing what class sits on top.
More adequate example would be multiple inheritance:
public abstract class MenuItem {
public string Name { get; set; }
public abstract void BringToTable();
}
// Notice Soda only inherits from MenuItem
public class Soda : MenuItem {
public override void BringToTable() { /* Bring soda to table */ }
}
// All food needs to be cooked (real food) so we add this
// feature to all food menu items
public interface IFood {
void Cook();
}
public class Pizza : MenuItem, IFood {
public override void BringToTable() { /* Bring pizza to table */ }
public void Cook() { /* Cook Pizza */ }
}
public class Burger : MenuItem, IFood {
public override void BringToTable() { /* Bring burger to table */ }
public void Cook() { /* Cook Burger */ }
}
Then you can use all of them as MenuItem and don't care about how they handle each method call.
public class Waiter {
public void TakeOrder(IEnumerable<MenuItem> order)
{
// Cook first
// (all except soda because soda is not IFood)
foreach (var food in order.OfType<IFood>())
food.Cook();
// Bring them all to the table
// (everything, including soda, pizza and burger because they're all menu items)
foreach (var menuItem in order)
menuItem.BringToTable();
}
}
Simple Explanation with analogy
No interface (Example 1):
No interface (Example 2):
With an interface:
The Problem to Solve: What is the purpose of polymorphism?
Analogy: So I'm a foreperson on a construction site. I don't know which tradesperson is going to walk in. But I tell them what to do.
If it's a carpenter I say: build wooden scaffolding.
If it's a plumber, I say: Set up the pipes
If it's a BJP government bureaucrat, I say, three bags full of cash, sir.
The problem with the above approach is that I have to: (i) know who's walking in that door, and depending on who it is, I have to tell them what to do. This typically makes code harder to maintain or more error prone.
The implications of knowing what to do:
This means if the carpenter's code changes from: BuildScaffolding() to BuildScaffold() (i.e. a slight name change) then I will have to also change the calling class (i.e. the Foreperson class) as well - you'll have to make two changes to the code instead of (basically) just one. With polymorphism you (basically) only need to make one change to achieve the same result.
Secondly you won't have to constantly ask: who are you? ok do this...who are you? ok do that.....polymorphism - it DRYs that code, and is very effective in certain situations:
with polymorphism you can easily add additional classes of tradespeople without changing any existing code. (i.e. the second of the SOLID design principles: Open-close principle).
The solution
Imagine a scenario where, no matter who walks in the door, I can say: "Work()" and they do their respect jobs that they specialise in: the plumber would deal with pipes, and the electrician would deal with wires, and a bureaucrat could specialise in extracting bribes and making double work for everyone else.
The benefit of this approach is that: (i) I don't need to know exactly who is walking in through that door - all i need to know is that they will be a type of tradie and that they can do work, and secondly, (ii) i don't need to know anything about that particular trade. The tradie will take care of that.
So instead of this:
if(electrician) then electrician.FixCablesAndElectricity()
if(plumber) then plumber.IncreaseWaterPressureAndFixLeaks()
if(keralaCustoms) then keralaCustoms.askForBribes()
I can do something like this:
ITradesman tradie = Tradesman.Factory(); // in reality i know it's a plumber, but in the real world you won't know who's on the other side of the tradie assignment.
tradie.Work(); // and then tradie will do the work of a plumber, or electrician etc. depending on what type of tradesman he is. The foreman doesn't need to know anything, apart from telling the anonymous tradie to get to Work()!!
What's the benefit?
The benefit is that if the specific job requirements of the carpenter etc change, then the foreperson won't need to change his code - he doesn't need to know or care. All that matters is that the carpenter knows what is meant by Work(). Secondly, if a new type of construction worker comes onto the job site, then the foreman doesn't need to know anything about the trade - all the foreman cares is if the construction worker (.e.g Welder, Glazier, Tiler etc.) can get some Work() done.
Summary
An interface allows you to get the person to do the work they are assigned to, without you having the knowledge of exactly who they are or the specifics of what they can do. This allows you to easily add new types (of trade) without changing your existing code (well technically you do change it a tiny tiny bit), and that's the real benefit of an OOP approach vs. a more functional programming methodology.
If you don't understand any of the above or if it isn't clear ask in a comment and i'll try to make the answer better.
Here are your examples reexplained:
public interface IFood // not Pizza
{
public void Prepare();
}
public class Pizza : IFood
{
public void Prepare() // Not order for explanations sake
{
//Prepare Pizza
}
}
public class Burger : IFood
{
public void Prepare()
{
//Prepare Burger
}
}
In the absence of duck typing as you can use it in Python, C# relies on interfaces to provide abstractions. If the dependencies of a class were all concrete types, you could not pass in any other type - using interfaces you can pass in any type that implements the interface.
The Pizza example is bad because you should be using an abstract class that handles the ordering, and the pizzas should just override the pizza type, for example.
You use interfaces when you have a shared property, but your classes inherit from different places, or when you don't have any common code you could use. For instance, this is used things that can be disposed IDisposable, you know it will be disposed, you just don't know what will happen when it's disposed.
An interface is just a contract that tells you some things an object can do, what parameters and what return types to expect.
Consider the case where you don't control or own the base classes.
Take visual controls for instance, in .NET for Winforms they all inherit from the base class Control, that is completely defined in the .NET framework.
Let's assume you're in the business of creating custom controls. You want to build new buttons, textboxes, listviews, grids, whatnot and you'd like them all to have certain features unique to your set of controls.
For instance you might want a common way to handle theming, or a common way to handle localization.
In this case you can't "just create a base class" because if you do that, you have to reimplement everything that relates to controls.
Instead you will descend from Button, TextBox, ListView, GridView, etc. and add your code.
But this poses a problem, how can you now identify which controls are "yours", how can you build some code that says "for all the controls on the form that are mine, set the theme to X".
Enter interfaces.
Interfaces are a way to look at an object, to determine that the object adheres to a certain contract.
You would create "YourButton", descend from Button, and add support for all the interfaces you need.
This would allow you to write code like the following:
foreach (Control ctrl in Controls)
{
if (ctrl is IMyThemableControl)
((IMyThemableControl)ctrl).SetTheme(newTheme);
}
This would not be possible without interfaces, instead you would have to write code like this:
foreach (Control ctrl in Controls)
{
if (ctrl is MyThemableButton)
((MyThemableButton)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableTextBox)
((MyThemableTextBox)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableGridView)
((MyThemableGridView)ctrl).SetTheme(newTheme);
else ....
}
In this case, you could ( and probably would ) just define a Pizza base class and inherit from them. However, there are two reasons where Interfaces allow you to do things that cannot be achieved in other ways:
A class can implement multiple interfaces. It just defines features that the class must have. Implementing a range of interfaces means that a class can fulfil multiple functions in different places.
An interface can be defined in a hogher scope than the class or the caller. This means that you can separate the functionality, separate the project dependency, and keep the functionality in one project or class, and the implementation of this elsewhere.
One implication of 2 is that you can change the class that is being used, just requiring that it implements the appropriate interface.
Consider you can't use multiple inheritance in C#, and then look at your question again.
I did a search for the word "composition" on this page and didn't see it once. This answer is very much in addition to the answers aforementioned.
One of the absolutely crucial reasons for using interfaces in an Object Oriented Project is that they allow you to favour composition over inheritance. By implementing interfaces you can decouple your implementations from the various algorithms you are applying to them.
This superb "Decorator Pattern" tutorial by Derek Banas (which - funnily enough - also uses pizza as an example) is a worthwhile illustration:
https://www.youtube.com/watch?v=j40kRwSm4VE
Interface = contract, used for loose coupling (see GRASP).
If I am working on an API to draw shapes, I may want to use DirectX or graphic calls, or OpenGL. So, I will create an interface, which will abstract my implementation from what you call.
So you call a factory method: MyInterface i = MyGraphics.getInstance(). Then, you have a contract, so you know what functions you can expect in MyInterface. So, you can call i.drawRectangle or i.drawCube and know that if you swap one library out for another, that the functions are supported.
This becomes more important if you are using Dependency Injection, as then you can, in an XML file, swap implementations out.
So, you may have one crypto library that can be exported that is for general use, and another that is for sale only to American companies, and the difference is in that you change a config file, and the rest of the program isn't changed.
This is used a great deal with collections in .NET, as you should just use, for example, List variables, and don't worry whether it was an ArrayList or LinkedList.
As long as you code to the interface then the developer can change the actual implementation and the rest of the program is left unchanged.
This is also useful when unit testing, as you can mock out entire interfaces, so, I don't have to go to a database, but to a mocked out implementation that just returns static data, so I can test my method without worrying if the database is down for maintenance or not.
Interfaces are for applying connection between different classes. for example, you have a class for car and a tree;
public class Car { ... }
public class Tree { ... }
you want to add a burnable functionality for both classes. But each class have their own ways to burn. so you simply make;
public class Car : IBurnable
{
public void Burn() { ... }
}
public class Tree : IBurnable
{
public void Burn() { ... }
}
You will get interfaces, when you will need them :) You can study examples, but you need the Aha! effect to really get them.
Now that you know what interfaces are, just code without them. Sooner or later you will run into a problem, where the use of interfaces will be the most natural thing to do.
An interface is really a contract that the implementing classes must follow, it is in fact the base for pretty much every design pattern I know.
In your example, the interface is created because then anything that IS A Pizza, which means implements the Pizza interface, is guaranteed to have implemented
public void Order();
After your mentioned code you could have something like this:
public void orderMyPizza(IPizza myPizza) {
//This will always work, because everyone MUST implement order
myPizza.order();
}
This way you are using polymorphism and all you care is that your objects respond to order().
I'm surprised that not many posts contain the one most important reason for an interface: Design Patterns. It's the bigger picture into using contracts, and although it's a syntax decoration to machine code (to be honest, the compiler probably just ignores them), abstraction and interfaces are pivotal for OOP, human understanding, and complex system architectures.
Let's expand the pizza analogy to say a full fledge 3 course meal. We'll still have the core Prepare() interface for all our food categories, but we'd also have abstract declarations for course selections (starter, main, dessert), and differing properties for food types (savoury/sweet, vegetarian/non-vegetarian, gluten free etc).
Based on these specifications, we could implement the Abstract Factory pattern to conceptualise the whole process, but use interfaces to ensure that only the foundations were concrete. Everything else could become flexible or encourage polymorphism, yet maintain encapsulation between the different classes of Course that implement the ICourse interface.
If I had more time, I'd like to draw up a full example of this, or someone can extend this for me, but in summary, a C# interface would be the best tool in designing this type of system.
Here's an interface for objects that have a rectangular shape:
interface IRectangular
{
Int32 Width();
Int32 Height();
}
All it demands is that you implement ways to access the width and height of the object.
Now let's define a method that will work on any object that is IRectangular:
static class Utils
{
public static Int32 Area(IRectangular rect)
{
return rect.Width() * rect.Height();
}
}
That will return the area of any rectangular object.
Let's implement a class SwimmingPool that is rectangular:
class SwimmingPool : IRectangular
{
int width;
int height;
public SwimmingPool(int w, int h)
{ width = w; height = h; }
public int Width() { return width; }
public int Height() { return height; }
}
And another class House that is also rectangular:
class House : IRectangular
{
int width;
int height;
public House(int w, int h)
{ width = w; height = h; }
public int Width() { return width; }
public int Height() { return height; }
}
Given that, you can call the Area method on houses or swimming-pools:
var house = new House(2, 3);
var pool = new SwimmingPool(3, 4);
Console.WriteLine(Utils.Area(house));
Console.WriteLine(Utils.Area(pool));
In this way, your classes can "inherit" behavior (static-methods) from any number of interfaces.
What ?
Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.
In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes
Now Why ?
Improves code re-usability
Lets say you want to draw Circle, Triangle.
You can group them together and call them Shapesand have methods to draw Circle and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.
With Interface you isolate the different implementation from the Contract
Live Scenario Day 1
You were asked to create an App to Draw Circle and Triangle
interface IShapes
{
void DrawShape();
}
class Circle : IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to Draw a Circle");
}
}
Class Triangle: IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to draw a Triangle");
}
}
static void Main()
{
List <IShapes> shapes = new List<IShapes>();
shapes.Add(new Circle());
shapes.Add(new Triangle());
foreach(var shape in shapes)
{
shape.DrawShape();
}
}
Live Scenario Day 2
If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());
An interface defines a contract between the provider of a certain functionality and the correspondig consumers. It decouples the implementation from the contract (interface). You should have a look at object oriented architecture and design. You may want to start with wikipedia: http://en.wikipedia.org/wiki/Interface_(computing)
There are a lot of good answers here but I would like to try from a slightlt different perspective.
You may be familiar with the SOLID principles of object oriented design. In summary:
S - Single Responsibility Principle
O - Open/Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
Following the SOLID principles helps to produce code that is clean, well factored, cohesive and loosely coupled. Given that:
"Dependency management is the key challenge in software at every scale" (Donald Knuth)
then anything that helps with dependency management is a big win. Interfaces and the Dependency Inversion Principle really help to decouple code from dependencies on concrete classes, so code can be written and reasoned about in terms of behaviours rather than implementations. This helps to break the code into components which can be composed at runtime rather than compile time and also means those components can be quite easily plugged in and out without having to alter the rest of the code.
Interfaces help in particular with the Dependency Inversion Principle, where code can be componentized into a collection of services, with each service being described by an interface. Services can then be "injected" into classes at runtime by passing them in as a constructor parameter. This technique really becomes critical if you start to write unit tests and use test driven development. Try it! You will quickly understand how interfaces help to break apart the code into manageable chunks that can be individually tested in isolation.
Soo many answers!
Giving my best shot. hehe.
So to begin, yes you could have used a concrete base and derived class here. In that case, you would have to do an empty or useless implementation for the Prepare method in the base class also making this method virtual and then the derived classes would override this Prepare method for themselves. This case, the implementation of Prepare in Base class is useless.
The reason why you chose to use an Interface is because you had to define a contract, not an implementation.
There is a IPizza type and it provides a functionality to Prepare. This is contract. How it is prepared is the implementation and it is not your lookout. It is responsibility of the various Pizza implementations.
An interface or an abstract class is preferred here over a concrete base class because you had to create an abstraction, i.e., the Prepare method. You cannot create an abstract method in a concrete base class.
Now you could say, why not use an abstract class?
So, when you need to achieve 100% abstraction, you need to go with Interface. But when you need some abstraction along with a concrete implementation, go with abstract class. It means.
Example: Lets say all your pizzas will have a base and base preparation will be the same process. However, all pizza types and toppings will vary. In this case you could create an Abstract class with an abstract method Prepare and a concrete method PreparePizzaBase.
public abstract class Pizza{
// concrete method which is common to all pizzas.
public PizzaBase PreparePizzaBase(){
// code for pizza base preparation.
}
public abstract void Prepare();
}
public class DeluxePizza: Pizza{
public void Prepare(){
var base=PreparePizzaBase();
// prepare deluxe pizza on pizza base.
}
}
The main purpose of the interfaces is that it makes a contract between you and any other class that implement that interface which makes your code decoupled and allows expandability.
Therese are ask really great examples.
Another, in the case of a switch statement, you no longer have the need to maintain and switch every time you want rio perform a task in a specific way.
In your pizza example, if want to make a pizza, the interface is all you need, from there each pizza takes care of it's own logic.
This helps to reduce coupling and cyclomatic complexity. You have to still implement the logic but there will be less you have to keep track of in the broader picture.
For each pizza you can then keep track of information specific to that pizza. What other pizzas have doesn't matter because only the other pizzas need to know.
The simplest way to think about interfaces is to recognize what inheritance means. If class CC inherits class C, it means both that:
Class CC can use any public or protected members of class C as though they were its own, and thus only needs to implement things which do not exist in the parent class.
A reference to a CC can be passed or assigned to a routine or variable that expects a reference to a C.
Those two function of inheritance are in some sense independent; although inheritance applies both simultaneously, it is also possible to apply the second without the first. This is useful because allowing an object to inherit members from two or more unrelated classes is much more complicated than allowing one type of thing to be substitutable for multiple types.
An interface is somewhat like an abstract base class, but with a key difference: an object which inherits a base class cannot inherit any other class. By contrast, an object may implement an interface without affecting its ability to inherit any desired class or implement any other interfaces.
One nice feature of this (underutilized in the .net framework, IMHO) is that they make it possible to indicate declaratively the things an object can do. Some objects, for example, will want data-source object from which they can retrieve things by index (as is possible with a List), but they won't need to store anything there. Other routines will need a data-depository object where they can store things not by index (as with Collection.Add), but they won't need to read anything back. Some data types will allow access by index, but won't allow writing; others will allow writing, but won't allow access by index. Some, of course, will allow both.
If ReadableByIndex and Appendable were unrelated base classes, it would be impossible to define a type which could be passed both to things expecting a ReadableByIndex and things expecting an Appendable. One could try to mitigate this by having ReadableByIndex or Appendable derive from the other; the derived class would have to make available public members for both purposes, but warn that some public members might not actually work. Some of Microsoft's classes and interfaces do that, but that's rather icky. A cleaner approach is to have interfaces for the different purposes, and then have objects implement interfaces for the things they can actually do. If one had an interface IReadableByIndex and another interface IAppendable, classes which could do one or the other could implement the appropriate interfaces for the things they can do.
Interfaces can also be daisy chained to create yet another interface. This ability to implement multiple Interfaces give the developer the advantage of adding functionality to their classes without having to change current class functionality (SOLID Principles)
O = "Classes should be open for extension but closed for modification"
To me an advantage/benefit of an interface is that it is more flexible than an abstract class. Since you can only inherit 1 abstract class but you can implement multiple interfaces, changes to a system that inherits an abstract class in many places becomes problematic. If it is inherited in 100 places, a change requires changes to all 100. But, with the interface, you can place the new change in a new interface and just use that interface where its needed (Interface Seq. from SOLID). Additionally, the memory usage seems like it would be less with the interface as an object in the interface example is used just once in memory despite how many places implement the interface.
Interfaces are used to drive consistency,in a manner that is loosely coupled which makes it different to abstract class which is tightly coupled.That's why its also commonly defined as a contract.Whichever classes that implements the interface has abide to "rules/syntax" defined by the interface and there is no concrete elements within it.
I'll just give an example supported by the graphic below.
Imagine in a factory there are 3 types of machines.A rectangle machine,a triangle machine and a polygon machine.Times are competitive and you want to streamline operator training.You just want to train them in one methodology of starting and stopping machines so you have a green start button and red stop button.So now across 3 different machines you have a consistent way of starting and stopping 3 different types of machines.Now imagine these machines are classes and the classes need to have start and stop methods,how you going to drive consistency across these classes which can be very different? Interface is the answer.
A simple example to help you visualize,one might ask why not use abstract class? With an interface the objects don't have to be directly related or inherited and you can still drive consistency across different classes.
public interface IMachine
{
bool Start();
bool Stop();
}
public class Car : IMachine
{
public bool Start()
{
Console.WriteLine("Car started");
return true;
}
public bool Stop()
{
Console.WriteLine("Car stopped");
return false;
}
}
public class Tank : IMachine
{
public bool Start()
{
Console.WriteLine("Tank started");
return true;
}
public bool Stop()
{
Console.WriteLine("Tank stopped");
return false;
}
}
class Program
{
static void Main(string[] args)
{
var car = new Car();
car.Start();
car.Stop();
var tank = new Tank();
tank.Start();
tank.Stop();
}
}
class Program {
static void Main(string[] args) {
IMachine machine = new Machine();
machine.Run();
Console.ReadKey();
}
}
class Machine : IMachine {
private void Run() {
Console.WriteLine("Running...");
}
void IMachine.Run() => Run();
}
interface IMachine
{
void Run();
}
Let me describe this by a different perspective. Let’s create a story according to the example which i have shown above;
Program, Machine and IMachine are the actors of our story. Program wants to run but it has not that ability and Machine knows how to run. Machine and IMachine are best friends but Program is not on speaking terms with Machine. So Program and IMachine make a deal and decided that IMachine will tell to Program how to run by looking Machine(like a reflector).
And Program learns how to run by help of IMachine.
Interface provides communication and developing loosely coupled projects.
PS: I’ve the method of concrete class as private. My aim in here is to achieve loosely coupled by preventing accessing concrete class properties and methods, and left only allowing way to reach them via interfaces. (So i defined interfaces’ methods explicitily).
I am having trouble with the concept of interfaces interacting with polymorphic types (or even polymorphic interfaces). I'm developing in C# and would appreciate answers staying close to this definition, although i think that still gives plenty of room for everyone to put forth an answer.
Just as an example, let's say you want to make a program to paint things. You define an interface for the actor that Paints, and you define an interface for the subject which is painted, Furthermore you have some subjects which can be painted in a more specific way.
interface IPainter {
void paint(IPaintable paintable);
}
interface IPaintable {
void ApplyBaseLayer(Color c);
}
interface IDecalPaintable : IPaintable {
void ApplyDecal(HatchBrush b);
}
I can imagine making a painter similar to the following:
class AwesomeDecalPainter : IPainter
{
public void paint(IPaintable paintable) {
IDecalPaintable decalPaintable = (IDecalPaintable)paintable;
decalPaintable.ApplyBaseLayer(Color.Red);
decalPaintable.ApplyDecal(new HatchBrush(HatchStyle.Plaid, Color.Green));
}
}
Of course this will throw if paintable does not implement IDecalPaintable. It immediately introduces a coupling between the IPainter implementation and the IPaintable that it operates on. However I also don't think it makes sense to say that AwesomeDecalPainter is not an IPainter just because it's use is limited to a subset of the IPaintable domain.
So my question is really four-fold:
Are interface compatible with
polymorphism at all?
Is it good
design to implement an IPainter that
can operate on IDecalPaintable?
What about if it can exclusively operate
on IDecalPaintable?
Is there any literature or source code that
exemplifies how interfaces and polymorphic types
should interact?
The interface of a class is meant as a tool for the "user" of that class. An interface is a public presentation for the class, and it should advertise, to anyone considering to use it, what methods and constants are available and accessible from the outside. So, as it name suggests, it always sits between the user and the class implementing it.
On the other hand, an abstract class is a tool aimed at helping the "implementor" of the classes that extend it. It is an infrastructure that can impose restrictions and guidelines about what the concrete classes should look like. From a class design perspective, abstract classes are more architecturally important than interfaces. In this case, the implementor sits between the abstract class and the concrete one, building the latter on top of the former.
So to answer your question simply, Interface is a "contract" for the code to respect. When uused this way, it applies more to inheritance that polymorphism.
Abstract classes, they define a 'type'. And when the concrete sub classes use abstract classes and redefine methods, add new ones etc ... there you see polymorphism in action.
I know this post may confuse you more, it didn't make sense to me until I learned design patterns. With a few simple patterns under your belt you will better understand the role of each object and how inheritance, polymorphism and encapsulation play hand in hand to build cleanly designed applications.
Good-Luck
Interfaces are not only compatible with polymorphism--they're essential to it. Part of the idea you seem to be missing is that if one has an interface like IPaintable, the expectation is that every object that implements it will provide some default method of being painted, typically encapsulating other methods which would configure the object in some useful fashion.
For example, an IPaintable interface might define a paint method:
void Paint(ICanvas canvas);
Note that the Paint method says nothing about what should be painted, nor what color, nor anything else. Various paintable objects would expose properties to control such things. A Polygon method, for example, might dispose OutlineColor and FillColor properties, along with a SetVertices() method. A routine that wants to paint a whole lot of objects could accept an IEnumerable(Of IPaintable) and simply call Paint on all of them, without having to know anything about how they'll be painted. The fact that an object is painted by calling Paint with no parameters other than the canvas upon which it should be painted in no way prevents the Paint method from doing all sorts of fancy gradient fills, texture mapping, ray tracing, or other graphical effects. The code which is commanding the painting would know nothing of such things, but the IPaintable objects themselves would hold all the information they needed and thus wouldn't need the calling code to supply it.
The problem is really that you have defined a vague interface, a contract is a more proper term. It's like you go into McDonalds and just order a burger:
interface Resturant
{
Burger BuyBurger();
}
The person taking your order will look a bit confused for a while, but eventually he/she will serve you any burger since you don't specify what you want.
Same thing here. Do you really just want to define that something is paintable? If you ask me, it's like asking for trouble. Always try to make interfaces as specific as possible. It's always better to have several small specific interfaces than a large general one.
But let's go back to your example. In your case, all classes only have to be able to paint something. Therefore I would add another more specific interface:
interface IPainter
{
void Paint(IPaintable paintable);
}
interface IDecalPainter : IPainter
{
void Paint(IDecalPaintable paintable);
}
interface IPaintable
{
void ApplyBaseLayer(Color c);
}
interface IDecalPaintable : IPaintable
{
void ApplyDecal(HatchBrush b);
}
class AwesomeDecalPainter : IDecalPainter
{
public void Paint(IPaintable paintable)
{
IDecalPaintable decalPaintable = paintable as IDecalPaintable;
if (decalPaintable != null)
Paint(decalPaintable);
else
paintable.ApplyBaseLayer(Color.Red);
}
public void Paint(IDecalPaintable paintable)
{
paintable.ApplyBaseLayer(Color.Red);
paintable.ApplyDecal(new HatchBrush(HatchStyle.Plaid, Color.Green));
}
}
I would recommend that you read about the SOLID principles.
Update
A more sound interface implementation
interface IPaintingContext
{
//Should not be object. But my System.Drawing knowledge is limited
object DrawingSurface { get; set; }
}
interface IPaintable
{
void Draw(IPaintingContext context);
}
class AwesomeDecal : IPaintable
{
public void Draw(IPaintingContext paintable)
{
// draw decal
}
}
class ComplexPaintableObject : IPaintable
{
public ComplexPaintableObject(IEnumerable<IPaintable> paintable)
{
// add background, border
}
}
Here you can create as complex painting items as possible. They are now aware what they paint on, or what other paintables are used on the same surface.
Am I understanding your question correctly?
I think your question is whether interface can exercise the essentials of inheritance ?
(ie. child interface inheriting from parent interface).
1) if that's the case, syntactically sure, why not?
2) as for the practicability, it may be of little value because, your child interfaces are not essentially reusing anything from your parent interface.