Test the Upcasting Rule - Java Language Basics

Java examples for Language Basics:Primitive Types

Description

Test the Upcasting Rule

Demo Code

class EmpUtil {/* w w w .  j av a 2s  .  c o m*/
  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 Bates");

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

    // Print names 
    EmpUtil.printName(emp);
    EmpUtil.printName(mgr); // Upcasting at work
  }
}
class Employee {
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}
class Manager extends Employee {   
  // No code is needed for now
}

Result


Related Tutorials