AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
Java downcast11/18/2023 ![]() When you want invoke a method on an instance, the methods you can call depends on multiple things, among the declared type of the instance, the modifier of the method and from where you call them. This seriously confuses me because we are able to access the subclasses' toString method but has to downcast the object in order to use the other methods namely getBaseSalary and setBaseSalary? Why is this the case? In order to invoke BasePlusCommissionEmployee's methods getBaseSalary and setBaseSalary on the current Employee object, a condition statement is used to check if the object reference is a BasePlusCommissionEmployee object by using the instanceof operator and if the condition is true the object has to be downcast from Employee to BasePlusCommissionEmployee type before invoking the methods mentioned. As a result, the output illustrates that the specific methods for each class are invoked and are resolved at execution time, based on the type of the object. The book further explains that the enhanced for loop iterates the array employees and invokes methods toString and earnings with Employee variable currentEmployee which is assigned the reference to a different Employee in the array on each iteration. get type name of each object in employees arrayįor (int j = 0 j < employees.length j++) "earned $%.2f%n%n", currentEmployee.earnings()) "new base salary with 10%% increase is: $%.2f%n", (BasePlusCommissionEmployee) currentEmployee ĮtBaseSalary(1.10 * employee.getBaseSalary()) If (currentEmployee instanceof BasePlusCommissionEmployee) determine whether element is a BasePlusCommissionEmployee generically process each element in array employeesįor (Employee currentEmployee : employees) ("Employees processed polymorphically:%n%n") "earned", basePlusCommissionEmployee.earnings()) Įmployees = basePlusCommissionEmployee HourlyEmployee, "earned", hourlyEmployee.earnings()) ĬommissionEmployee, "earned", commissionEmployee.earnings()) SalariedEmployee, "earned", salariedEmployee.earnings()) 06) īasePlusCommissionEmployee basePlusCommissionEmployee = The PayrollSystemTest contains the main method to run the application. The other Employee subclasses are as per normal. Below is the uml for the example I'm following.įor all objects of BasePlusCommissionEmployee they are to given a 10% increase on their base salary. ![]() However, I'm pretty stuck with understanding the concept of downcasting. ![]() I'm reading up a book on Java and currently on the Polymorphism topic as well as how to downcast a reference variable.
0 Comments
Read More
Leave a Reply. |