Java examples for Object Oriented Design:Method Overloading
How the Compiler Chooses the Most Specific Method from Several Versions of an Overloaded Method
public class Main { public double add(int a, int b) { System.out.println("Inside add(int a, int b)"); double s = a + b; return s;/*from w ww . j a va2 s .co m*/ } public double add(double a, double b) { System.out.println("Inside add(double a, double b)"); double s = a + b; return s; } public void test(Employee e) { System.out.println("Inside test(Employee e)"); } public void test(Manager e) { System.out.println("Inside test(Manager m)"); } public static void main(String[] args) { Main ot = new Main(); int i = 10; int j = 15; double d1 = 1.4; double d2 = 2.5; float f1 = 1.3F; float f2 = 1.5F; short s1 = 2; short s2 = 6; ot.add(i, j); ot.add(d1, j); ot.add(i, s1); ot.add(s1, s2); ot.add(f1, f2); ot.add(f1, s2); Employee emp = new Employee(); Manager mgr = new Manager(); ot.test(emp); ot.test(mgr); emp = mgr; ot.test(emp); } } class Employee { private String name = "Unknown"; public void setName(String name) { this.name = name; } public String getName() { return name; } public boolean equals(Object obj) { boolean isEqual = false; // We compare objects of the Employee class with the objects of // Employee class or its descendants if (obj instanceof Employee) { // If two have the same name, consider them equal. Employee e = (Employee) obj; String n = e.getName(); isEqual = n.equals(this.name); } return isEqual; } } class Manager extends Employee { // No code is needed for now }