Java - Inheritance Upcasting and Downcasting

is a

"is-a" means to create a subclass, which is a more specific type of the superclass.

For example, a Manager is a specific type of Employee. An Employee is a specific type of Object.

Inheritance guarantees that whatever behavior is in Employee will be present in Manager.

If code works with a class, it will work with the class's subclass.

Example

Consider the following snippet of code:

Employee emp;
emp = new Employee();
emp.setName("Mary");
String name = emp.getName();

A Manager object can be assigned to an Employee variable

Employee emp;
emp = new Manager(); 
emp.setName("Mary");
String name = emp.getName();

Upcasting

All of the following assignments are allowed and they are all examples of upcasting:

Object obj;
Employee emp;
Manager mgr;
PartTimeManager ptm;

// An employee is always an object
obj = emp;

// A manager is always an employee
emp = mgr;

// A part-time manager is always a manager
mgr = ptm;

// A part-time manager is always an employee
emp = ptm;

// A part-time manager is always an object
obj = ptm;

Demo

class Employee {
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }/*  w  w w . ja va 2  s  . co  m*/

  public String getName() {
    return name;
  }
}

class Manager extends Employee {

}

class EmpUtil {
  public static void printName(Employee emp) {
    // Get the name of employee
    String name = emp.getName();

    // Print employee name
    System.out.println(name);
  }
}

public class Main {
  public static void main(String[] args) {
    Employee emp = new Employee();
    emp.setName("Mary");

    Manager mgr = new Manager();
    mgr.setName("Tom"); // Inheritance of setName() at work

    // Print names
    EmpUtil.printName(emp);
    EmpUtil.printName(mgr); // Upcasting at work
  }
}

Result

The following type of assignment is always allowed:

Object obj = new AnyJavaClass(); // Upcasting

Downcasting

not every employee is a manager (downcasting).

During downcasting, add a casting.

mgr = (Manager)emp; // OK. Downcast at work