0

So i have the abstract class Worker, which has the abstract function computePay.

The two children classes of this class are HourlyWorker and FixedWorker, now i have provided the implementation of computePay in both these classes.Now my code says

Worker[] w=new worker[2];
w[0]=new HourlyWorker;
w[1]=new FixedWorker;

now when i say w[0].computePay how am i sure that which computePay is called, i know the one from the child class will be called, but which one?

i.e. If my both the child classes have different implementation of the computePay function, will the following code give me the desired result?

w[0].computePay //Prints the pay as per the implementation in HourlyWorker;
w[1].computePay //Prints the pay as per the implementation in FixedWorker;

Also i heard about the instance of operator/keyword, but i dont know will it be of any use here?

1
  • It's common practice to use println statements for debugging. Commented Sep 6, 2011 at 12:29

3 Answers 3

7

Yes, Java will make sure that the "correct" method gets called.

No need for manual dispatch using instanceof.

i know the one from the child class will be called, but which one?

A basic concept of OOP is that you don't need to know. You are programming to the interface defined in your abstract class, and don't need to know about which implementation is being used here (or what it does).

Sign up to request clarification or add additional context in comments.

2 Comments

thanks.. will accept the answer as soon as the stackoverflow allows me to.
@thilo +1 for the link @ karan i guess all answer says the same thing I hope you are more clear now.
2

I know the one from the child class will be called, but which one?

The one of the actual type of your object. So if your object is a HourlyWorker (initialized with new HourlyWorker()) you will call the computePay method of this type.

The instance of keyword is used to test if an object is of a specified type. It should not be used in good designs (except when overriding equals). It is of no use here. On the contrary, you should rely on the polymorphism as you suggested.

Comments

0

The methods in java are by default virtual(like in CPP you have to use virtual keyword), so java will make sure the methods are called in respect of object rather than the reference. Abstract method are pure virtual function of C++

Also note that instanceof wont be useful here, so avoid it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.