This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Derived Class & Method Calling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Derived Class & Method Calling" Watch "Derived Class & Method Calling" New topic
Author

Derived Class & Method Calling

Deroga Rivera
Greenhorn

Joined: Aug 04, 2005
Posts: 13
I read some of the past forum posts but none of them quite get to what I am trying to figure out. I have the following classes:


With the following to test a few things:


I understand the concept of why a manager object uses the getSalary method in the manager class and why an employee will use the employee method.

I also understand why an employee cannot access manager methods but a manager can access employee methods.

What I do not understand.
When I created an Employee and assigned a Manager type to it.
1. It created an employee, I am ok so far.
2. It uses the Manager getSalary. I am not ok with this.
3. Attempts to access the setBonus method in manager fails

It seems like the instance I called em is both a manager and an employee depending on what it wants to do. I don't understand why it calls the manager getSalary but will not allow code to call manager methods.

I mark the areas of the code that I don't understand why they act as they do with hopefully that will make it easier to follow.

Thanks!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

Welcome to JavaRanch!

When you write

Employee em = new Manager();

you create a Manager object, but you're referring to it as an Employee -- which is OK because a Manager is an Employee. Remember, though, that it's really a Manager.

To address your questions:

1) You created a Manager, not an Employee per se. A Manager is a kind of an Employee.

2) This is actually a fabulous thing. It's called polymorphism and the fact that this happens is extremely important.

Imagine you have to write a method to print paychecks for all the staff at this company. The input to this method has to be an object representing each of the staff members. Because a Manager is-a-kind-of an Employee, and you can store a Manager in an Employee variable (see (1), above) we can pass an array of Employees to this method.



So we get an array of Employees and we ask each one for its salary and then print a paycheck. But note that some of the Employees in the array are Managers. We want to print a correct paycheck for every member of the staff. So when we call getSalary() on an Employee, we want the version in Employee; but if the object is really a Manager, then we want the version in Manager. And that's exactly what Java will do! This idea of polymorphism comes up time and time again -- it's really important.

3) You can't call getBonus() because the compiler, looking at the source code, isn't sure that an Employee is really a Manager. The JVM knows that when the program is running, but the compiler doesn't know if it's going to work, so it refuses to do it.

But you can tell the compiler "When the program is running, I know (for some reason) that this Employee is really a Manager". The way you tell the compiler that is called a typecast or cast. You can do this:

Employee e = new Manager();
...
Manager m = (Manager) e;

That bold part is the cast. It tells the compiler that e is really referring to a Manager, and so the assignment is OK. Henceforth, you can call m.getBonus(), because all Manager objects are known to have that method.

I hope all this has helped you.
[ August 04, 2005: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Deroga Rivera
Greenhorn

Joined: Aug 04, 2005
Posts: 13
I understand the concept of polymorphism, thanks for clarify it.
---
Employee e = new Manager();
...
Manager m = (Manager) e;


Wouldn't this be the same as Manager m = new Manager();
---

So I guess I understand why it does what it does. What I don't understand is what purpose doing something like Employee em = new Manager() has. I have seen this kind of usage in some code samples, mostly with Date/Calendar classes but I don't understand why anyone would use it.

If you create an Manager but treat it as an employee you lose the abilities of the manager and you don't appear to gain anything. I understand the concept of having an array of employees and managers and being able to make the same call to either type and have Java figure out what should be done, but what possible advantage could you have with the Employee em = new Manager() type of statement?

Thanks for the very helpful response, I am getting a handle on this.
Deroga.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Ah. You're just thinking too hard!

There's really no point to the two line example of mine you quoted. It's a kind of shorthand, I guess, for something like



But remember that this whole discussion started with you asking why you can't call getBonus() on an Employee variable that's pointing to a Manager. The real truth is that in real code you rarely want to do this. If you do want to do this, you use a cast, as I've shown -- but you make a mental note to revisit the design, if possible, and fix things so you can use polymorphism to hand the differences instead. Look at the code above and think about how I could change it to be a polymorphic method on Employee, so that I could simply call

e.doSomething();

and be done with it.

OK? It's true that often times short examples can be very contrived. See my comment in this thread earlier today. Anyone who actually wrote

i = i++;

or any variation of that in a real application should be beaten soundly with a rubber hose. But beginners are still expected (for reasons that escape me!) to understand it.
Deroga Rivera
Greenhorn

Joined: Aug 04, 2005
Posts: 13
I know some things won't be clear until I have worked with them for a while longer and continue to think about it in this way. The next time I run across and example like

SomeClass myName = new SomeOtherClass();

I will look at it more carefully and try to understand why they chose to do it that way. With the information you gave here I should be able to figure that out.

Thanks again for all of your help.
Deroga.
Megs Maquito
Ranch Hand

Joined: May 18, 2005
Posts: 84
am I correct to say that with:



you don't actually create a Manager object but instead create an object referring to Manager?


I'm a Hood Ornament
Arun Kumarr
Ranch Hand

Joined: May 16, 2005
Posts: 513

I'm afraid. No.
You actually do create a Manger Object {new Manager(x,y)} and have the variable "em" referring to the Manager Object you've created.


If you are not laughing at yourself, then you just didn't get the joke.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Deroga Rivera:
I know some things won't be clear until I have worked with them for a while longer and continue to think about it in this way. The next time I run across and example like

SomeClass myName = new SomeOtherClass();

I will look at it more carefully and try to understand why they chose to do it that way. With the information you gave here I should be able to figure that out.

Thanks again for all of your help.
Deroga.


Here's a simple example that might help clarify why polymorphism is so powerful. Let's say you are creating a MS Paint-style program that allows the user to draw various geometrical shapes. It would make sense to have a Shape class that declares a method called paint() since every Shape can be painted on the screen. However, if we create different subclasses, say Rectangle, Triangle, and Circle, they are each painted differently. Each of these subclasses will implement the paint() method in the expected manner. However, in the program it might be handy to have a Shape reference and ignore which specific kind of Shape it is. If the reference is named s, then we can call s.paint() and the correct shape will be painted on the screen.

This is even more powerful if we want to store a list of shapes either as an array or using a class from the Collections framework. Let's use the former and make declare something like

Now we can store any variety of Shape objects in this array whether they are Circles, Rectangles, or Triangles. We can also paint them by calling shapeArray[i].paint() without knowing which specific kind of shape each one is.

I hope this illustrates how polymorphism is useful. I'm assuming that you understand arrays with the last example. If not, don't worry about it too much. That should be coming up soon as you continue to learn Java. Also, the Collections framework that I mentioned earlier uses polymorphism extensively, both in defining the hierarchy of different Collection classes and in storing Objects in each Collection. If you want to learn more about polymorphism, I think this is a great portion of the API to use in that regards.

I hope you come back with more questions in the future. And Keep Coding!

Layne


Java API Documentation
The Java Tutorial
Deroga Rivera
Greenhorn

Joined: Aug 04, 2005
Posts: 13
Thanks again for your helpful responses.

I do understand the concept and usage of polymorphism and have used it in some small applications. I have been programming for awhile at a basic to intermediate level, I just stopped for the last 6 or 8 months so when Java 5 came out I took it as an opportunity to revisit some of the more basic concepts to see them from a different viewpoint. When I got to this I didn't just accept it as I did the first time through!

---

What confuses me about the usage is why someone would do something like
Date() myDate = new Calendar();
or
Employee() emp = new Manager();

Instead of keeping the class the same on both sides. I realize the power of polymorphism does not need to know if it is an employee or manager but what hasn't sunk in yet is why you wouldn't just use
Calendar() myDate = new Calendar();
and
Manager() emp = new Manager();

To me, it seems clearer as to what is going on and I can't find an advantage to the other method. Any insight that might help me make sense of that?

Thanks!
Deroga.
Jayesh Lalwani
Ranch Hand

Joined: Nov 05, 2004
Posts: 502


but in real-life, the code might be something like this


Textbooks are merely using a short-hand equivalent to make the code easier to read. Many times, developers will use the same shorthand if they are in a rush, because it's easier to replace the call to "new" with the call to factory method without changing rest of the code.


The advantage of using a factory method is that you can easily change that part of the code that initializes the employee without changing rest of the code. For example, you could change the above code to




or you can add functionality like getting the employee/manager from the database



There are other advantages and many other better ways of doing this. The above code is for illustration only. Factory patterns are a whole new topic, and a discussion of factory patterns can occupy it's own thread. There are plenty of resources that talk about advantages of using a factory pattern.

If you are starting to learn java, then I would encourage you to let some non-consequential items slip by, and concentrate on the fundamentals for now. At this time, you may not understand why exactly the textbook authors have done something, but in time you will. As long as you concentrate of grasping the basics described in the lesson, you should do fine

ETA: Oops, I missed the part where you said you have been programming in java. I take back the last part. I would encourage you to read up on patterns, if you haven't already.

[ August 08, 2005: Message edited by: Jayesh Lalwani ]
[ August 08, 2005: Message edited by: Jayesh Lalwani ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Derived Class & Method Calling
 
Similar Threads
Scanner class question
Question regarding Cloneable interface and Subclasses
Inheritence query??
please check this code
Casting problem