aspose file tools
The moose likes Beginning Java and the fly likes How to achieve runtime polymorphism in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How to achieve runtime polymorphism in Java" Watch "How to achieve runtime polymorphism in Java" New topic
Author

How to achieve runtime polymorphism in Java

vijay kumarg
Ranch Hand

Joined: Dec 14, 2006
Posts: 105
This is the question I faced from one of my friend who has got 4 certfications in J2se and J2EE.
My explanation below does not satisfied him he says. Please let me know where I go wrong, need to have a more concise approach or I miss anything ?

" The argument of a method if we supply a super type then it can able to take any sub types of that super type and able to execute the relevant version of that method "
so we are able to execute a method version of a particular type at runtime depending on the requirement ".

Thanks,
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32833
    
    4
Difficult to understand the question.

You have a superclass (maybe abstract, maybe concrete) which has several subclasses. Each subclass therefore has the same methods as the superclass.
You declare each of the objects by the name of the superclass (or an interface, eg List<XYZ> myList; . . . myList = new ArrayList<XYZ>();), and each of the objects has methods of the same name.
By calling the methods on objects of the subclasses, you can get different behaviour from each.
To preserve polymorphism, don't add methods to subclasses which aren't in their superclass.
Gavin Tranter
Ranch Hand

Joined: Jan 01, 2007
Posts: 333
Hi
Sorry I know this is not my question/thread, perhaps i have miss understood the question/answer, but i dont understand the statement:

To preserve polymorphism, don't add methods to subclasses which aren't in their superclass.


Why would you need to do this? wont the JDK "perserve polymorphism", by using the object type reference to determine what methods are available rather then using the objects actual type.
Then at runtime the JVM choses the method to execute based on actual object type rather then reference type.

So no matter how many methods you add to a subtype, if you reference it by its supertype you will never be able to access those more specialised methods (without a cast).

Isnt polymorphism by definion achieved at runtime? A subtype being assumed (due to the rules of java) to be able to do what a supertype can, so a subtype should be able to slot into any space reserved for its super type?

Or perhaps I have been total confused by this thread
G
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Gavin Tranter:

Isnt polymorphism by definion achieved at runtime?


Depends on what definition for polymorphism you use...

For example, the template mechanism in C++ is often referred to as a form of "compile time polymorphism".


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
My answer to the question would be that runtime polymorphism at the source level is achieved by using non-private instance methods.

If that doesn't satisfy your friend, I would ask him to clarify the question.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
So no matter how many methods you add to a subtype, if you reference it by its supertype you will never be able to access those more specialised methods (without a cast).


I'm not sure that was a question, but if you were checking to see if you had it straight, you did.

Sometimes you'll hear us talk about the Liskov Substitution Principle: If you have code that works with some concrete class, it should work equally well with any subclass. This turns out to be hard enough to do that many of us avoid extending any concrete class if we can. You can extend a concrete class and still satisfy LSP if you carefully add new methods and don't override any methods. But, as you said, you can only use those new methods if you reference the object as the subtype.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32833
    
    4
Maybe I was exaggerating when I said not to add methods, but Stan James has reminded us of the substitution principle. You should be able to call the object by a superclass name and still be able to gain access to all requisite members. So you sayList is an interface which is an extreme example of an abstract superclass. You can say myList.add() or myList.remove(), which are examples of polymorphism, because
  • They are methods inside the List interface, so inherited.
  • The methods of the same name are implemented differently.
  • All the books have the example of Employees in:-We have a problem with the SalesRep class. The payCommission method isn't declared in Employee, so you can't say:-The compiler would complain about the call to payCommission(). You would have to reference as the subtype, as we have just been told, and Stan James has told how difficult it can be to make the classes match real-world situations.
    [ February 21, 2007: Message edited by: Campbell Ritchie ]
    Gavin Tranter
    Ranch Hand

    Joined: Jan 01, 2007
    Posts: 333
    Stan, sorry, your right, the quote you made, wasnt a question it was a statement, I was refering to the original question that started the thread.

    Campbell:



    Ah, I dont consider the final line to even be polymorphic, it is not something I would consider doing (I know its an example) payCommission is not a behaviour of the any super type of SalesRep, so it plays no part in the polymorphic behaviour of SalesRep or Empolyee.
    I am not sure its possible to override a method to break polymorphism either, although perhaps errors from overriding are more likely to turn up as runtime exceptions. I just dont see how, with the rules for overridding the way they are it could cause an issue.

    I guess it comes down to that (in my mind) (attempting to) calling a subtype method from a supertype method is not polymorphic, perhaps that is why I am having problem/missunderstanding with your statements about it be difficult. On the over hand it could be that I might write simplistic/bad code.

    I have been a developer for years, too long perhaps, and have recently choosen to do SCJP, still learning, and started to take more interest in OOA/OOD and design patterns because of this. Some of it does seem to be common sense that you would do anyway, but I am learning new things, and as you can see I am not affarid to question and hold up my current understand when I come across something "new" or that seems to challenge what I thought I knew.

    G
    Stan James
    (instanceof Sidekick)
    Ranch Hand

    Joined: Jan 29, 2003
    Posts: 8791
    I am learning new things, and as you can see I am not affarid to question and hold up my current understand when I come across something "new" or that seems to challenge what I thought I knew.


    You found a good place for that kind of attitude, for sure.

    As Campbell pointed out, that little snippet you quoted won't compile. Java's strict typing helps you avoid some errors. Other languages would let you try it and maybe get a "no such method" exception or something.

    It's pretty easy to mess up the expectations of others when you override a method. For example, what if you extended LinkedList and made the size() method always return 1? You could pass an instance into a method that works perfectly with LinkedList but won't work at all with yours. Alan Holub wrote that Extends is Evil. That's a deliberate exaggeration just to get your juices flowing, but he has some pretty good examples of the risks of extending concrete classes.

    Scroll down to the OO, UML, etc. forum to talk this kind of stuff every day.
    vijay kumarg
    Ranch Hand

    Joined: Dec 14, 2006
    Posts: 105
    Hello Ranchers,
    I am sorry for not making my question clearer.
    From all your replies I finally came to a conclusion like below.
    What I know about runtime polymorphism in java is " sub types of a super can be equated to that super type and through that refernce method of a specific sub type can be executed at runtime except private and static methods"
    Am I following the correct trial?

    Thanks,
    [ February 21, 2007: Message edited by: vijay kumarg ]
    Gavin Tranter
    Ranch Hand

    Joined: Jan 01, 2007
    Posts: 333

    For example, what if you extended LinkedList and made the size() method always return 1? .....


    Ah, thats an extreme example, and I get the point now, I think, see, I guess I was thinking does the method slot into place now its overridden, not, does it actaul still adhere to its contract/behaviour that the supertype method defined.

    Thanks, sorry it took a bit to get there, I will be more aware when I override in future.

    G
     
    I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
     
    subject: How to achieve runtime polymorphism in Java
     
    Similar Threads
    Can a private method be overridden by a subclass ?
    Overriding Exception error
    Difference between overridding & redefining a method
    Calling Superclass version of an Overridden Method
    Doubt in K&B SCJP 5: topic _OVERRIDING