I have two objects:
- Employee E
- PTEmployee PE
I need to do the following manipulation
EV=E
EV=PE
I believe I would need to do the following:
var EV = E
But then when I set EV = PE, I cannot access the Class PTEmployee methods, because the IDE thinks that the variable EV is still of Employee Type.
This is what I have tried:
Employee E = new Employee(name, ssn, position, new Date(dobMonth, dobDay, dobYear), pay);
PTEmployee PE = new PTEmployee(name, ssn, position, new Date(dobMonth, dobDay, dobYear), nHours, wages);
var EV = E;
EV = PE;
Given
Why does the second assignment downcast?
Inferred type using
varThe Java compiler and your IDE (e.g. method-suggestions or autocompletion) both have the type inferred already with the first and initial assignment.
All further assignments will not change the type of this variable.
See also:
How to declare the variable to accept any sub-class ?
Use-case allowing the shorthand
varNow lets assume the use-case that you have a work-force of 2 employees that should get paid. But the accountant does not care about their time-percentage, only calculating their pay is important. The type of employment is not important.
In the first use-case scenario, the for-each loop, the
vardeclaration is sufficient and shortens our loop-head. We are only interested to call the methods of base-classEmployee, so we can usevarsafely.Use-case requiring distinct subtypes
For the HR staff, which has to write the contract, the working-hours and contracted salary model however is very important. So the type of employee is accurately defined.
In the second use-case scenario, you can see, that because we expect to deal with different types of employees in the
hireCandidatemethod, we also declared the variables with different types as needed.