File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Polymorphism is the deebil Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Polymorphism is the deebil" Watch "Polymorphism is the deebil" New topic
Author

Polymorphism is the deebil

Hansjoachim Vonhortenschiem
Greenhorn

Joined: Mar 03, 2011
Posts: 15
Sorry to post redundate info requests, but I've just finished the nights reading, (no, I'm not in school.. I graduated 2 years ago, computer science, and can't find a job.. thought I would become a java guy and am doing self study) and the topic was polymorphism in a book about designs patterns.
I should probably know this, but you can understand how when you learn something new, you can sometimes forget what you "thought" you knew before...haha.

Anyway, here's a made up scenario with the question to follow:



now the question: what if I wanted to add something to CartoonDuck that was native to only ducks that were in cartoons?. For instance, a speak() method, because most if not all cartoon ducks can speak. Say that I wanted daffy to be able to say "I'm a talking duck!".
My first impulse would be to add a method speak() to the class CartoonDuck. But because the reference variable "daffy" is polymorphic and of type Duck, it can "see" only those things that are Duck..... so, what do you do ?

I have a feeling that the answer might be to create yet another behavior class that handles talking ducks. This class would implement the same interface(s) as the other behavior classes I would think. But dang, it would seem that a programmer could just reach into cartoonDuck and tweak it alittle without having to dedicate yet another class for such a simple requirement. And might I add, do so without causing the java universe to implod on itself.

Thanks....
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

If you want some of your duck specific classes wants to have speak() method, i think you can have Speakable interface with speak() method in it and have your specific duck class implement this Speakable interface.

if you want to call speak() method then you would need to check instanceof and cast it to Speakable reference and call speak() method.


SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
Hansjoachim Vonhortenschiem
Greenhorn

Joined: Mar 03, 2011
Posts: 15
That's what I was afraid of....

I'm having trouble wrapping my thoughts around the concept of having to take everything related to a particular class/object, extract it from the class and basically pimp it out to some other class and an accompanying interface...

If I had some super class "Duck", and then had several child classes that represented specific ducks, "MallardDuck, CartoonDuck, DecoyDuck, RubberDuck"etc etc, then everything that defines the uniqueness of each specific duck (the things not inherited from "Duck") would be extracted and given to some other class that implements some interface. So, in the end, these specific child classes are basically stripped bare.

And so, I'm finding it difficult to even see the point in having the child classes to begin with. It would seem that it would just be better to have the super class "Duck" and then have several behavior classes (that do not extend Duck) to represent a Duck. Then each instance of Duck would be named with a specific duck name in order to pseudo represent an actual specific duck.

In other words, in my confused state, it would seem that inheritance is pointless !

An example would be a class that simply prints a word like "Java". Does that mean I need to have a class that handles a J, another to handle the a's and then yet another to handle the v? And of course, I'm sure I would need an interface "letters" to be implemented by yet another class "words"...... it just seems like everything has to be broken down into it's most simplest form, regardless of how many sub-components it generates and then reconstructed into some intricate and complicated entity that in the end will still do no more than print the word "Java"......

I'm really bummed at the moment : (

The concept of composition, I believe, is what I'm struggling to integrate into my inheritance-centric thoughts.....make sense ?

I would love to have someone that understands my jibberish respond with a clearer description of how inheritance, composition and polymorphism each find their respective places in the Java Universe...

Thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18120
    
  39

Fuman Choo wrote:
In other words, in my confused state, it would seem that inheritance is pointless !


Inheritance, like any other tool in programming, doesn't work for everything -- and for certain scenarios, it is probably pointless... but that doesn't make inheritance itself pointless.

For example, let's say you want to write a Duck Store application that people will use to try out and buy ducks. You can write the complete application -- and this application will work with anything that's a Duck. Heck, someone can invent a new type of duck in the future, and your code will work for it too. Now, of course, you can't use the new feature of the new type of Duck, but you don't need those features, you just want to work with a Duck.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
Inheritance is not pointless, as Henry has already told you. But it has its rules, and only works when those rules are followed.

One of those rules says that a subclass must be a superclass. A Duck is a kind of bird, which can swim and fly and lives near water.
So can you say a MallardDuck "is a" Duck? Yes; in fact most ducks in Britain are mallards. Can you say a DecoyDuck "is a" Duck? Dubious. Can you say a RubberDuck "is a" Duck? I would think not. Can you say a CartoonDuck "is a" Duck? Dubious. If you can't say something "is a" something else, then inheritance won't work.

Another rule is that one must be able to use all methods in the superclass in the subclass, without anything unexpected happening. This was defined by Barbara Liskov about 23 years ago; Google for Liskov Substitution Principle and yo should find something useful. You will also find discussion about i in this recent thread.

There is also type extension and functional extension and I can never remember which way round each is. One is easy to use the other difficult. In one case you are not adding any new methods, only overriding existing methodsIn the other case you are adding new methodsNow you see how much more awkward that sort of inheritance is to implement. It is slightly more elegant following ramesh maredu's suggestion of creating an interface . . . but you see how awkward it can be to add a new method.
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
I don't have any quarrel with responses so far; I do have some thoughts that might prove helpful.

Your example code has the driver getting a variable that is of type Duck. The idea is that, if there is a subclass being used, the caller does not know what kind of subclass that is, and does not attempt to use any of the characteristics that are specific to that subclass. As soon as I find a place in my code where I would be forced to use "instanceof", or something similar to determine the internals of the object I'm dealing with, I examine it carefully to figure out why my design forces me to do that. I won't say I never use it, but I only plan to in very unusual cases.

I think your difficulty might stem from trying to make inheritance do things that it was not intended to do. It is not a general-purpose typing system. It is not meant to make it easy for your code to get an object that is a member of a general type and then suddenly start using it as a more specific type, except within the bounds of inheriting behavior within its own rules.

As for whether composition is "what you're looking for", I don't think that question has a general answer. Composition is a way of doing things, as is inheritance, they each have their advantages and limitations. But the OO languages support certain things with inheritance that are difficult to do any other way.

Take the classic example of a program that provides for a collection of shapes on a screen. Imagine a shape class (abstract, I would think), and its subclasses rectangle, circle, triangle, etc. Shape can define the signature for one or more methods for drawing the shape, and each subclass can implement it/them. The same can be said of getCenterpoint(), getEnclosingRectangle(), and some other ones.

But the base class can define properties, with getters and setters, for color, line pattern, opacity, relationship to other shapes, and many other things. The subclasses don't have to have any code for these at all; they are characteristics of JUST the shape, and by organizing the code this way, the programmer writes these things one time, the subclasses inherit them, and all is well.

I get confused when people try to assert that composition is preferable to inheritance, and even that there's something undesirable about inheritance. I can't tell what they're talking about. Obviously they've never written a Swing application. Inheritance is a great tool, it is useful for many things but not necessarily what you can dream up that it might have been good for.

rc
Kiaamaa Liammes
Ranch Hand

Joined: Oct 03, 2009
Posts: 32

I remember finding it difficult to grasp the OOAD concepts when starting off , I found downloading bluej and trying out examples helping me get a grasp on OOAD concepts and clear many of my doubts.


SCJP ,SCWCD
Hansjoachim Vonhortenschiem
Greenhorn

Joined: Mar 03, 2011
Posts: 15
It may help if I were to divulge that I was currently reading "Head First - Design Patterns" from Oreilly publishers. According to the authors, the material in the book is both confirmed and supported by the "team" here at JavaRanch.

Knowing that, then if you have this particular literature at your disposal you can look at the example in chapter one instead of trying to translate my horrid representation of it. Now, as I said before, it just seems to me (keep in mind I've yet to grasp the "big" picture), that they are stripping the specific duck classes bare of any unique attributes they might otherwise have and farming them out to "behavior" classes that implement some "behavior-esque" interface. The point being to attempt to encapsulate all specific duck behavior and then program to an interface. Meaning, I believe, to make that which changes about specific ducks easy to manipulate and change whilest simultaneously refering to any specific objects with a high level reference..i.e, a super class reference or interface reference (this is where polymorphism slips into the conversation).

That is all well and good. The problem I'm having is seeing the true benefit of taking something as straight-forward as: SuperClass "Duck" (contains all things relevant to "any" duck), is extended by one or more specific (child class) ducks (containing all things specific to a particular duck). And then with this, I can simply say Or maybe,

Instead, the authors want to create, what seems to me, a class and accompanying interface for every single aspect of a duck. And then to use the highest level reference variable they can, coupled with the concept of composition to create this horrendous monstrosity of " go around the world just to get around the block".

Maybe I just assumed that inheritance was infallable and could handle almost anything....... newbies think as such I suppose : (

Thanks for the replies and the patience... It's just some hard ground to plow is all...
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18120
    
  39

Fuman Choo wrote:
Instead, the authors want to create, what seems to me, a class and accompanying interface for every single aspect of a duck. And then to use the highest level reference variable they can, coupled with the concept of composition to create this horrendous monstrosity of " go around the world just to get around the block".


The authors are trying to teach you polymorphism, with the goal of teaching the subject. It won't be optimal. It could probably be done easier without polymorphism. And it may even be somewhat silly.

You need to learn the subject -- and have some faith that it will be useful. IMO, OOP don't work too well for very small programs, but you need very small programs to learn. So, yeah, it seems like an overkill, but you are trying to learn the subject at this point.

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Polymorphism is the deebil
 
Similar Threads
Creating Objects
The Ducks are back
Design Patterns Study Group
I'm probably overlooking something very stupid...
why am i able to call a static method using an object of that class ...