Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to achieve runtime polymorphism in Java  RSS feed

 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 55715
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 55715
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Posts: 333
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
    Posts: 8791
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
    Posts: 105
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
    Posts: 333
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    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
     
    sampath kumar chindirala
    Greenhorn
    Posts: 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The standard definition of polymorphism is ability to take more than one form. Polymorphism can be divided into two categories.
    1. Static polymorphism.
    2. Dynamic polymorphism.

    In static polymorphism at compile time only which method needs to be called will be decided. Method overriding is an example of static polymorphism. Consider the below example.



    In the above example when we call Test() then always only first method will be called. When we call Test("some string") always second method will be called. It means decision is already made at compile time.

    But Run time polymorphism means taking decision at run time. You can achieve runtime polymorphism by using method overriding. Take below example.



    In the above class vehicle object is same but we are storing car and bus objects in vehicle; So if we store car object in vehicle then when we call vehicle.MyName() then it will call MayName() method of car. So if we store bus object in vehicle then when we call vehicle.MyName() then it will call MayName() method of bus. Like this based the passed object it will take decision at runtime. This is called run time polymorphism.
     
    Campbell Ritchie
    Marshal
    Posts: 55715
    163
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Welcome to the Ranch

    Most of us here think “compile‑time polymorphism” is an inaccurate term and never use it.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!