• Post Reply Bookmark Topic Watch Topic
  • New Topic

polymorphism?  RSS feed

 
Jolie Lee
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i've read this part of code in a book, but i don't seems to understand the explantion given. Pls advise.

public abstract class Employee
{
.....
public String toString()
{
}
}

public final class Boss extends Employee
{
...

public String toString()
{
}
}

public class Test
{
Employee ref;
Boss b = new Boss ("John", "Smith", 800.00);

ref = b;

ref.toString();
}

my questions is at class Test, ref = b, i do not understand why it needs to do that. according to the book, if ref.toString will called the class Boss's toString method instead of calling class Employee's toString method.

if that so, why can't i just use b.toString() to call?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could - it would make no difference.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you're missing the point here. You CAN just call b.toString(). but the neat thing here is that you have an Employee variable, pointing to a Boss object. this works because a Boss IS AN Employee.

in this example, it doesn't get you a lot. but if i were to make up an array of Employees, i could populate each one with different kinds of objects, as long as they are all Employees. i could have Bosses, Managers, CEOs, factoryWorkers, Accountants... as long as all of these derive directly or indirectly from Employee.

life is then pretty cool when i iterate through my array. i don't have to stop and check each one to see what it is and call that classes toString() method...


that gets very ugly very fast, and is hard to maintain. if somebody comes along and adds a CFO kind of employee, my for loop gets broken.

what i can do is just this:

since everything that derives from Employee will have a toString method (either it's own implementation, or the one it inherits), I DON'T EVEN NEED TO KNOW EXACTLY WHAT CLASS IT IS. i KNOW it's an employee, so i can call it's toString() method. the JVM will make sure to call the most specific one it can, automagically calling the CEO's version for a CEO, the factoryWorkers for them, etc.

and the really beautiful part is, with this loop, somebody can add a brand new class i've never heard of, and as long as it derives from Employee, i'll get it's version of toString().

hope that helps!!!
 
Jolie Lee
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred, thanks a lot. i think i hv a clearer picture now.

so this is call polymorphism?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!