Practical example of Polymorphism
Question:
Can anyone please give me a real life, practical example of Polymorphism? My professor tells me the same old story I have heard always about the +
operator. a+b = c
and 2+2 = 4
, so this is polymorphism. I really can’t associate myself with such a definition, since I have read and re-read this in many books.
What I need is a real world example with code, something that I can truly associate with.
For example, here is a small example, just in case you want to extend it.
>>> class Person(object):
def __init__(self, name):
self.name = name
>>> class Student(Person):
def __init__(self, name, age):
super(Student, self).__init__(name)
self.age = age
Answers:
Check the Wikipedia example: it is very helpful at a high level:
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'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
# prints the following:
#
# Missy: Meow!
# Mr. Mistoffelees: Meow!
# Lassie: Woof! Woof!
Notice the following: all animals “talk”, but they talk differently. The “talk” behaviour is thus polymorphic in the sense that it is realized differently depending on the animal. So, the abstract “animal” concept does not actually “talk”, but specific animals (like dogs and cats) have a concrete implementation of the action “talk”.
Similarly, the “add” operation is defined in many mathematical entities, but in particular cases you “add” according to specific rules: 1+1 = 2, but (1+2i)+(2-9i)=(3-7i).
Polymorphic behaviour allows you to specify common methods in an “abstract” level, and implement them in particular instances.
For your example:
class Person(object):
def pay_bill(self):
raise NotImplementedError
class Millionare(Person):
def pay_bill(self):
print "Here you go! Keep the change!"
class GradStudent(Person):
def pay_bill(self):
print "Can I owe you ten bucks or do the dishes?"
You see, millionares and grad students are both persons. But when it comes to paying a bill, their specific “pay the bill” action is different.
A common real example in Python is file-like objects. Besides actual files, several other types, including StringIO and BytesIO, are file-like. A method that acts as files can also act on them because they support the required methods (e.g. read
, write
).
A C++ example of polymorphism from the above answer would be:
class Animal {
public:
Animal(const std::string& name) : name_(name) {}
virtual ~Animal() {}
virtual std::string talk() = 0;
std::string name_;
};
class Dog : public Animal {
public:
virtual std::string talk() { return "woof!"; }
};
class Cat : public Animal {
public:
virtual std::string talk() { return "meow!"; }
};
void main() {
Cat c("Miffy");
Dog d("Spot");
// This shows typical inheritance and basic polymorphism, as the objects are typed by definition and cannot change types at runtime.
printf("%s says %sn", c.name_.c_str(), c.talk().c_str());
printf("%s says %sn", d.name_.c_str(), d.talk().c_str());
Animal* c2 = new Cat("Miffy"); // polymorph this animal pointer into a cat!
Animal* d2 = new Dog("Spot"); // or a dog!
// This shows full polymorphism as the types are only known at runtime,
// and the execution of the "talk" function has to be determined by
// the runtime type, not by the type definition, and can actually change
// depending on runtime factors (user choice, for example).
printf("%s says %sn", c2->name_.c_str(), c2->talk().c_str());
printf("%s says %sn", d2->name_.c_str(), d2->talk().c_str());
// This will not compile as Animal cannot be instanced with an undefined function
Animal c;
Animal* c = new Animal("amby");
// This is fine, however
Animal* a; // hasn't been polymorphed yet, so okay.
}
Polymorphism in Java:- Polymorphism means "more form" this is allow us to perform a single task in different ways. For the polymorphism we use method overloading and method overriding.
Method Overloading :- When defined two or more method within the same class that’s method name is same but their parameters are different. That case these methods is overloaded and this process is called Method Overloading. Method overloading is support compile time polymorphism. Overloaded methods have different return type.
Most Read:-Exception Handling in Java
Example:-
class OverloadingExample{
display(int a){
System.out.println("Display first method");
}
display(int a, int b){
System.out.println("Display second method");
}
display(int a, double b){
System.out.println("Display third method");
}
}
class Main {
public static void main(String [] args){
OverloadingExample example = new OverloadingExample();
example.display(10);
example.display(10, 20);
example.display(10, 15.56);
}
}
Output:- Display first method
Display second method
Display third method
Most Read:- interface in Java
Example:- In this example we using inheritance. When we create a OverloadingExample class and we create a display function after that we create another class second and there is create another display name function with same name and different signature of super class. class name second is extended by OverloadingExample.
Example:-
class OverloadingExample{
display(int a){
System.out.println("Display first method");
}
}
class Second extends OverloadingExample {
display(int a, int b){
System.out.println("Display second method");
}
}
class Main {
public static void main(String [] args){
Second example = new Second();
example.display(10);
example.display(10, 20);
}
}
Output:- Display first method
Display second method
Method Overriding:- When a method in a sub class has the same name and signature as a method of its super class. Then the method of sub class is overriden the method super class, that process is called Method Overriding. Method overriding support run time polymorphism.
Example:- We create a two display name method in super class and sub class. Sub class access all the properties and behaviours of super class so when class the method display in Main class its replace the super class method name display with the sub class method display. Overriding is used when we require to replace with new features in program on old function.
Example:-
class OverloadingExample{
display(){
System.out.println("Display OverloadingExample class ");
}
}
class Second extends OverloadingExample {
display(){
System.out.println("Display second class");
}
}
class Main {
public static void main(String [] args){
Second example = new Second();
example.display();
}
}
Output:- Display second method
Most Read:- What is function in Java and description of Call by value and call by Reference
Difference between Method Overloading and method overriding ?
Method Overloading:
- In this methods name is same but signature are different
- that is support compile line polymorphism
- In this methods return types is may or may not equal
- In this may or may not require to use of inheritance
Method Overriding
- In this use static keyword
- In this we use access modifiers
Method Overriding:
- In this methods name and signatures both same
- It is support run time polymorphism
- In this methods return type must be same
- In this require inheritance.
- In this we cannot use static keyword
- In this we cannot use access modifiers
you want to read more Java Topics of Java visit Click on this link
Can anyone please give me a real life, practical example of Polymorphism? My professor tells me the same old story I have heard always about the +
operator. a+b = c
and 2+2 = 4
, so this is polymorphism. I really can’t associate myself with such a definition, since I have read and re-read this in many books.
What I need is a real world example with code, something that I can truly associate with.
For example, here is a small example, just in case you want to extend it.
>>> class Person(object):
def __init__(self, name):
self.name = name
>>> class Student(Person):
def __init__(self, name, age):
super(Student, self).__init__(name)
self.age = age
Check the Wikipedia example: it is very helpful at a high level:
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'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
# prints the following:
#
# Missy: Meow!
# Mr. Mistoffelees: Meow!
# Lassie: Woof! Woof!
Notice the following: all animals “talk”, but they talk differently. The “talk” behaviour is thus polymorphic in the sense that it is realized differently depending on the animal. So, the abstract “animal” concept does not actually “talk”, but specific animals (like dogs and cats) have a concrete implementation of the action “talk”.
Similarly, the “add” operation is defined in many mathematical entities, but in particular cases you “add” according to specific rules: 1+1 = 2, but (1+2i)+(2-9i)=(3-7i).
Polymorphic behaviour allows you to specify common methods in an “abstract” level, and implement them in particular instances.
For your example:
class Person(object):
def pay_bill(self):
raise NotImplementedError
class Millionare(Person):
def pay_bill(self):
print "Here you go! Keep the change!"
class GradStudent(Person):
def pay_bill(self):
print "Can I owe you ten bucks or do the dishes?"
You see, millionares and grad students are both persons. But when it comes to paying a bill, their specific “pay the bill” action is different.
A common real example in Python is file-like objects. Besides actual files, several other types, including StringIO and BytesIO, are file-like. A method that acts as files can also act on them because they support the required methods (e.g. read
, write
).
A C++ example of polymorphism from the above answer would be:
class Animal {
public:
Animal(const std::string& name) : name_(name) {}
virtual ~Animal() {}
virtual std::string talk() = 0;
std::string name_;
};
class Dog : public Animal {
public:
virtual std::string talk() { return "woof!"; }
};
class Cat : public Animal {
public:
virtual std::string talk() { return "meow!"; }
};
void main() {
Cat c("Miffy");
Dog d("Spot");
// This shows typical inheritance and basic polymorphism, as the objects are typed by definition and cannot change types at runtime.
printf("%s says %sn", c.name_.c_str(), c.talk().c_str());
printf("%s says %sn", d.name_.c_str(), d.talk().c_str());
Animal* c2 = new Cat("Miffy"); // polymorph this animal pointer into a cat!
Animal* d2 = new Dog("Spot"); // or a dog!
// This shows full polymorphism as the types are only known at runtime,
// and the execution of the "talk" function has to be determined by
// the runtime type, not by the type definition, and can actually change
// depending on runtime factors (user choice, for example).
printf("%s says %sn", c2->name_.c_str(), c2->talk().c_str());
printf("%s says %sn", d2->name_.c_str(), d2->talk().c_str());
// This will not compile as Animal cannot be instanced with an undefined function
Animal c;
Animal* c = new Animal("amby");
// This is fine, however
Animal* a; // hasn't been polymorphed yet, so okay.
}
Polymorphism in Java:- Polymorphism means "more form" this is allow us to perform a single task in different ways. For the polymorphism we use method overloading and method overriding.
Method Overloading :- When defined two or more method within the same class that’s method name is same but their parameters are different. That case these methods is overloaded and this process is called Method Overloading. Method overloading is support compile time polymorphism. Overloaded methods have different return type.
Most Read:-Exception Handling in Java
Example:-
class OverloadingExample{
display(int a){
System.out.println("Display first method");
}
display(int a, int b){
System.out.println("Display second method");
}
display(int a, double b){
System.out.println("Display third method");
}
}
class Main {
public static void main(String [] args){
OverloadingExample example = new OverloadingExample();
example.display(10);
example.display(10, 20);
example.display(10, 15.56);
}
}
Output:- Display first method
Display second method
Display third method
Most Read:- interface in Java
Example:- In this example we using inheritance. When we create a OverloadingExample class and we create a display function after that we create another class second and there is create another display name function with same name and different signature of super class. class name second is extended by OverloadingExample.
Example:-
class OverloadingExample{
display(int a){
System.out.println("Display first method");
}
}
class Second extends OverloadingExample {
display(int a, int b){
System.out.println("Display second method");
}
}
class Main {
public static void main(String [] args){
Second example = new Second();
example.display(10);
example.display(10, 20);
}
}
Output:- Display first method
Display second method
Method Overriding:- When a method in a sub class has the same name and signature as a method of its super class. Then the method of sub class is overriden the method super class, that process is called Method Overriding. Method overriding support run time polymorphism.
Example:- We create a two display name method in super class and sub class. Sub class access all the properties and behaviours of super class so when class the method display in Main class its replace the super class method name display with the sub class method display. Overriding is used when we require to replace with new features in program on old function.
Example:-
class OverloadingExample{
display(){
System.out.println("Display OverloadingExample class ");
}
}
class Second extends OverloadingExample {
display(){
System.out.println("Display second class");
}
}
class Main {
public static void main(String [] args){
Second example = new Second();
example.display();
}
}
Output:- Display second method
Most Read:- What is function in Java and description of Call by value and call by Reference
Difference between Method Overloading and method overriding ?
Method Overloading:
- In this methods name is same but signature are different
- that is support compile line polymorphism
- In this methods return types is may or may not equal
- In this may or may not require to use of inheritance
Method Overriding - In this use static keyword
- In this we use access modifiers
Method Overriding:
- In this methods name and signatures both same
- It is support run time polymorphism
- In this methods return type must be same
- In this require inheritance.
- In this we cannot use static keyword
- In this we cannot use access modifiers
you want to read more Java Topics of Java visit Click on this link