This topic is now archived and is closed to further replies.


[java] Polymorphism

Recommended Posts

skap20    122
I am taking a class on Java and I am very confused here. We just had a test question which was the following:
class Base
  void display() { System.out.println("Base"); }
class Derived extends Base
  void display() { System.out.println("Derived"); }

// In main:
Base b = new Base();
Derived d = new Derived();
Base bd = new Derived();
The question was to list the order of the displays. I thought it was Base Derived Base, but it turns out the correct answer was Base Derived Derived. Now, when I run the equivalent code in C++ (the language I am more familiar with) I get Base Derived Base (the answer I put). So my question is, what gives? I thought both Java and C++ were object oriented. Are there no set rules governing what OOP means with respect to polymorphism? Or could it be caused by a "feature" of the particular Java implementation used by my school? -------------------- Nicholas Skapura AIM: skap35

Share this post

Link to post
Share on other sites
HenryApe    120
In C++ you would have to declare the display function 'virtual' to get the same result. All functions in Java behave as C++'s virtual functions do. In Java, you call super.display() in the derived class if you want the behavior of the Base class's display function.

Virtual calls carry a performance overhead over static calls (the behavior you get without the virtual keyword in C++). One reason all functions in C++ aren't virtual is that C++ is not able to optimize away all unnecessary virtual calls because it is not runtime compiled like Java.

[edited by - HenryAPe on August 8, 2003 9:23:27 AM]

Share this post

Link to post
Share on other sites
Kentaro    122
Java and C++ are both object-oriented. Java just follows the paradigm much better than C++ does. Even those two languages seem to fall short of being OO when compared to, say, Eiffel.

Late binding is one of the most powerful applications of the concept of polymorphism. That C++ requires you to use the ''virtual'' keyword is probably for the reason pointed out above: for optimum performance only the methods you know are going to be overridden need to be declared virtual. I don''t think it''s a good idea because you never know what methods from your class somebody else is going to want to override and if they need to override a method you haven''t declared virtual, they''re going to be missing out on late binding which just makes their code a lot harder to write than it needs to be.

All of that is just my opinion, of course. This forum doesn''t need another language flame war...

Over the centuries, mankind has tried many ways of combating the forces of evil...prayer,
fasting, good works and so on. Up until Doom, no one seemed to have thought about the
double-barrel shotgun. Eat leaden death, demon...
-- Terry Pratchett

Share this post

Link to post
Share on other sites