Home > database >  How to change a variable type in Java?
How to change a variable type in Java?

Time:06-08

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;

CodePudding user response:

Given

// base class
class Employee{}

// part-time (PT) employee inherits from employee
class PTEmployee extends Employee {}

Inferred type using var

// renamed EV, E and PE to follow 
// Java-naming conventions: lower-case variable names
Employee e = .. // initialization omitted
PTEmployee pe = .. // initialization omitted


var ev = e; // type of local variable ev gets inferred as Employee
System.out.println(ev.getClass()); // debug-print the type

// now we assign another instance of the same (Employee) or a sub-type (PTEmployee)    
ev = pe;  // type of ev is still Employee (the assigned instance is down-casted)
System.out.println(ev.getClass()); // debug-print the type

See also:

CodePudding user response:

When we use a variable with the reserved word var, its typing is determined at initialization, which is why when you assign another type of class to this variable, you do not have access to its methods, and the IDE behaves quite correctly. For more information, you can read more about it in the following link https://openjdk.java.net/projects/amber/guides/lvti-faq#Q6

CodePudding user response:

So, when you first initialize the variable "EV" you need to declare that EV is a type of PTEmployee, not Employee. Like this

PTEmployee ev = e;
ev = pe;

And then after this you can access PTEmployee class's methods.

  • Related