Monday, January 9, 2012

Downcasting in Java

Downcasting

  • An upcast reference can be downcast to a subclass through explicit casting. For example:
    Employee e = new Manager(...);
    // ...
    Manager m = (Manager) e;
    • The object referenced must actually be a member of the downcast type, or else a ClassCastException run-time exception occurs.
  • You can test if an object is a member of a specific type using the instanceof operator, for example:
    if (obj instanceof Manager) { // We've got a Manager object }
public class EmployeeDemo {
    public static void main(String[] args) {
        final Employee e1 = new Employee("John", "555-12-345", "john@company.com");
        final Employee e2 = new Employee("456-78-901", 1974);
        e2.setName("Tom");
        Employee em = new Manager("Bob", "345-11-987", "Development");

        Employee.setBaseVacationDays(15);
        e2.setExtraVacationDays(5);
        em.setExtraVacationDays(10);

        if (em instanceof Manager) {
            Manager m = (Manager) em;
            m.setResponsibility("Operations");
        }

        e1.print("COOL EMPLOYEE");
        e2.print("START OF EMPLOYEE", "END OF EMPLOYEE");
        em.print("BIG BOSS");
    }
}
This would print:
BIG BOSS
Name: Bob
SSN: 345-11-987
Email Address: null
Year Of Birth: 0
Vacation Days: 25
Responsibility: Operations

No comments: