Polymorphism, what it is and what it is not [duplicate] - oop

This question already has answers here:
What is polymorphism, what is it for, and how is it used?
(29 answers)
Closed 9 years ago.
I have been working on oop on different programming language, I have used different manuals and i realized that practically all of them explained polymorphism differently, although I am fine with all their explanation in terms of getting to use it but can anyone just explain this concept in a lay man general term and concept with practical example?
Thanks
Reply appreciated

Here is a direct copy paste from wikipedia explaining xavi Lopez example:
"There are lots out there. For instance, this is a classical one: an Animal can makeSound(). A subclass of Animal called Dog will bark when implementing makeSound() and another one named Cat will meow. The makeSound() method behaves differently for an Animal depending on which is the actual subclass of the instance. – Xavi López"
abstract class Animal {
abstract String talk();
}
class Cat extends Animal {
String talk() { return "Meow!"; }
}
class Dog extends Animal {
String talk() { return "Woof!"; }
}
void lets_hear(Animal a) {
println(a.talk());
}
void main() {
lets_hear(new Cat());
lets_hear(new Dog());
}
As you can see, the animal has sever different extensions. So depending on animal type, a different thing will be printed.
The output looks like:
>>Meow!
>>Woof!

Related

How to make Perl 6 class final?

For example, I have such code:
class Foo {}
class Bar is Foo {}
While this action usefulness is arguable, is it possible to prohibit inheritance from Foo?
There's no built-in way in the Perl 6 language to prohibit inheritance of a class, and this was a deliberately taken design decision. It's also not clear one could achieve this even with meta-programming, since the act of inheritance is driven by the subclass, with the parent class having no say in the process.
It is, however, possible to mark individual methods as not being inherited, by declaring them as a submethod instead of a method.
class P {
submethod m() { say "not inherited" }
}
class C is P {
}
say ?P.can('m'); # True
say ?C.can('m'); # False

Why not use instanceof operator in OOP design?

It has been repeatedly said that the instanceof operator should not be used except in the equals() method, otherwise it's a bad OOP design.
Some wrote that this is a heavy operation, but it seems that, at least java, handles it pretty well (even more efficiently than Object.toString() comparison).
Can someone please explain, or direct me to some article which explains why is it a bad design?
Consider this:
Class Man{
doThingsWithAnimals(List<Animal> animals){
for(Animal animal : animals){
if(animal instanceOf Fish){
eatIt(animal);
}
else if(animal instanceof Dog){
playWithIt(animal);
}
}
}
...
}
The decision of what to do with the Animal, is up to the Man. Man's desires can also change occasionally, deciding to eat the Dog, and play with the Fish, while the Animals don't change.
If you think the instanceof operator is not the correct OOP design here, please tell how would you do it without the instanceof, and why?
instanceof simply breaks the Open/Close principle. and/or Liskov substitution principle
If we are not enough abstract because of instanceof usage, each time a new subclass makes an entrance, the main code gathering the logic of the application might be updated.
This is clearly not what we want, since it could potentially break the existing code and reduce its reusability.
Therefore, a good usage of polymorphism should be preferred over the basic use of conditional.
There's a good blog post called When Polymorphism Fails which is about this kind of scenario. Basically, you're right that it should be up to the Man to decide what to do with each kind of Animal. Otherwise, the code becomes fragmented and you end up violating principles such as Single Responsibility and Law of Demeter.
It wouldn't make sense to have code such as e.g. the following:
abstract class Animal {
abstract void interactWith(Man man);
}
class Fish extends Animal {
#Override
void interactWith(Man man) {
man.eat(this);
}
}
class Dog extends Animal {
#Override
void interactWith(Man man) {
man.playWith(this);
}
}
In that example, we're putting Man's logic outside of the Man class.
The problem with instanceof is that if you have a large amount of Animals, you'll end up with a long if-else-if for every one of them. It's hard to maintain and prone to errors where e.g. a new type of Animal is added, but you forget to add it to the if-else-if chain. (The visitor pattern is partly a solution to the latter problem, because when you add a new type to the visitor class, all of the implementations stop compiling and you're forced to go update them all.)
However, we can still use polymorphism to make the code simpler and avoid instanceof.
For example, if we had a feeding routine such as:
if (animal instanceof Cat) {
animal.eat(catFood);
} else if (animal instanceof Dog) {
animal.eat(dogFood);
} else if (...) {
...
}
We could eliminate the if-else-if by having methods such as Animal.eat(Food) and Animal.getPreferredFood():
animal.eat(animal.getPreferredFood());
With methods such as Animal.isFood() and Animal.isPet(), the example in the question could be written without instanceof as:
if (animal.isFood()) {
eatIt(animal);
} else if (animal.isPet()) {
playWithIt(animal);
}
instanceof is a type system escape hatch. It can be used to do really evil things, like make generics not really generic, or extend a class hierarchy with ad-hoc virtual methods that never appear in the visible interface of those classes. Both of these things are bad for long-term maintainability.
More often than not, if you find yourself wanting to use instanceof, it means that there is something wrong with your design. Breaking the type system should always be a last resort, not something to be taken lightly.
I do not think your particular example warrants using instanceof. The object-oriented way to do this is to use the visitor pattern:
abstract class Animal {
def accept(v: AnimalVisitor)
}
trait Edible extends Animal {
def taste : String
def accept(v: AnimalVisitor) = v.visit(this)
}
trait Pet extends Animal {
def growl : String
def accept(v: AnimalVisitor) = v.visit(this)
}
abstract class AnimalVisitor {
def visit(e: Edible)
def visit(p: Pet)
}
class EatOrPlayVisitor {
def visit(e: Edible) = println("it tastes " + e.taste)
def visit(p: Pet) = println("it says: " + p.growl)
}
class Chicken extends Animal with Edible {
def taste = "plain"
}
class Lobster extends Animal with Edible {
def taste = "exotic"
}
class Cat extends Animal with Pet {
def growl = "meow"
}
class Dog extends Animal with Pet {
def growl = "woof"
}
object Main extends App {
val v = new EatOrPlayVisitor()
val as = List(new Chicken(), new Lobster(), new Cat(), new Dog())
for (a <- as) a.accept(v)
}
NOTE: I am aware that Scala has case classes, but I wanted to provide a general object-oriented solution.
using instance of is a bad practise because in the OOP there is no need to check what the class is,
if the method is compatible you should to be able to call it with such arguments, otherwise design is spoiled, flawed,
but it exist the same way as goto in C and C++,
I think sometimes it might be easier to integrate a bad code using instance of but if you make your own proper code avoid it
so basically this is about of programming style what is good and what is bad,
when and why
in some curcumstances bad style is used, because sometimes the code quality is secondary, perhaps
sometimes the goal is to make the code not easy to understand by others so that would be the way to do it

OOP - How this relationship could be done in Object-Oriented Programming

Suppose there is a class A and it has many instances from class B, and in A, it will have some shared attributes for B to access. Simply I can write this type, I just want to know if there are any pattern or some other good way to make this relationship in OOP.
My idea is straightforward :
class A {
protected int shared;
public List<B> bList;
int getShared ()
{
return shared;
}
}
class B {
protected A _a;
B (A a) {
this._a = a;
}
void hello () {
print (this._a.getShared());
}
}
As I am pretty much a novice in OOP, so I think maybe there some pattern can do this better, looking forward your ideas. Thanks.
Your code is looking like Mediator pattern. Except that classically Mediator (A class) has a set of different objects for interacting with or between them without explicit references.

Simulate abstract classes and abstract methods in Objective C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating an abstract class in Objective C
In Java I like to use abstract classes to make sure that a bunch of classes has the same basic behavior, e.g.:
public abstract class A
{
// this method is seen from outside and will be called by the user
final public void doSomething()
{
// ... here do some logic which is obligatory, e.g. clean up something so that
// the inheriting classes did not have to bother with it
reallyDoIt();
}
// here the actual work is done
protected abstract void reallyDoIt();
}
Now that if class B inherits from class A, it only has to implement reallyDoIt().
How to make this in Objective C? Is it at all possible? Is it feasible in Objective C? I mean the whole paradigm seems to be different in Objective C e.g. from what I understand there is no way to forbid overriding a method (like in Java with 'final')?
Thanks!
There is no actual constraint on not overriding a method in objective c. You can use a protocol as Dan Lister suggested in his answer but this is only good to enforce your conforming class to implement a certain behavior declared in that protocol.
A solution for an abstract class in objective c could be :
interface MyClass {
}
- (id) init;
- (id) init {
[NSException raise:#"Invoked abstract method" format:#"Invoked abstract method"];
return nil;
}
This way you can prevent methods in your abstract class to be invoked (but only at run-time unlike languages like java which can detect this when on compile-time).
You'll want to use something called Protocols I think.

Best practice for enforcing type safety in polymorphic inheritance hierarchies [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I seem to run into this situation quite a lot and have yet to find a solution that I find acceptable.
Quite often I will have parallel inheritance hierarchies where a method in one hierarchy gets passed the matching class from the other hierarchy as a parameter.
Here is an example that probably explains this better.
abstract class Animal
{
public virtual void Eat(Food f)
{
}
}
abstract class Food
{
}
class LionFood : Food
{
}
class ElephantFood : Food
{
}
class Lion : Animal
{
public override void Eat(Food f)
{
// It is only ever valid to pass LionFood here as the parameter.
// passing any other type of Food is invalid and should be prevented
// or at least throw an exception if it does happen.
}
}
In the past, I have usually made the base class generic to allow the implementing concrete class to define the type as follows..
abstract class Animal<T> where T : Food
{
public abstract void Eat(T f);
}
class Lion : Animal<LionFood>
{
public override void Eat(LionFood f)
{
}
}
At first this seems like a very good solution because it provides compile-time type safety. But the more I use it, the more I am starting to think that using generics in this way is infact an anti-pattern. The problem is that the Animal base class cannot be used in a polymorphic way. You cannot, for example, easily write a method that will process any type of Animal regardless of its actual concrete type.
Every time I use this generics solution, I always seem to end up with covariant and contravariant interfaces all over the place just to try and provide the polymorphic behaviour I want. This gets out of hand pretty quickly and some functionality is not possible simply because the correct interface cannot be provided.
Of course another option is to not use generics and perform runtime type checking in the Eat method like this:
public override void Eat(Food f)
{
if (f.GetType() != typeof(LionFood))
{
throw new Exception();
}
}
This is better than nothing I suppose but I'm not a huge fan of it simply because of the lack of compile-time type safety.
So after all that.. My question is.. What is the best practice to provide polymorphic behaviour while at the same time ensuring some type safety?
Is there some OO design trick or pattern that I am missing that will allow me to avoid the parallel inheritance hierarchies all together?
I appreciate that this question is somewhat subjective, but there are points available for everyone who contributes and I'll choose the best response as the answer.
Thanks for looking.
Edit:
Having thought about this I realise that my example given doesn't really make sense. Of course it is not possible to use Animal in a polymorphic way because the type passed to Eat will always depend on the actual underlying type of Animal (which the initiator of a polymorphic call will not know)! I need to think of a better example that illustrates my actual situation.
I think common sense and the requirements of the domain will dictate the proper approach. Working with this example, I'd do like this
public class Lion:Animal
{
public override void Eat(Food f)
{
Eat(f as LionFood);
}
public void Eat(LionFood food)
{
//check for null food
//actually consume it
}
}
Edit
I think using generics is not suited in this case, because what if an Animal can play with a Toy, hunt a specific Animal and so on. You can have a number of methods with arugments that implement an abstraction, it's awkward to use generics every time there is a method with an argument that uses polymorhpism.
Ok, could that be what you want? Sometimes, when you can't articulate what you want to do, what you want is actually a mixin.
template<typename base>
class Eater: public base {
template<typename T>
Eat(T (extends Food) food) { // you can do that extends thing in C++ but I won't bother
// register what's eaten, or do whatever
base::Eat(food);
}
}
class Lion {
Eat(LionFood food) {
cout<<"Hmm delicious!";
}
}
int main() {
Eater<Lion> lion;
lion.eat(LionFood());
return 0;
}
This'll give you a nice compiler error if you try to feed grass to the lion.