What is Polymorphism? and Overloading Methods

What is Polymorphism?

The word polymorphism, strictly defined, means "many forms".

  • This assignment is perfectly legal. An Employee can be a Manager.
  • However, the following does not compile:
            emp.setDeptName ("Marketing"); // Compile error
  • The Java compiler recognizes the emp variable only as an Employee object. Because the Employee class does not have a setDeptName method, it shows an error.
The object-oriented programming languages such as java, polymorphism is the ability to refer to an object using either its actual form or a parent form.

This is particularly useful when creating a general-purpose business method. For Example,you can raise the salary of any Employee object(parent or child) by simply passing the object reference to a general-purpose business method that accepts an Employee object as an argument.

Overloading Methods

Your design may call for several methods in the same class with the same name but with different arguments.

  • Java permits you to reuse a method name for more than one method.
  • Two rules applied to overloaded methods:
  1. Argument lists must differ.
  2. Return types can be different.
  • Therefore, the following is not legal:

You might want to design methods with the same intent(name), like print, to print out several different types.  You could design a method for each type:

printInt(int i)
printFloat(float f)
printString(String s)

But this would be tedious and not very object-oriented. Instead, you can create a reusable method name and just change the argument list. This process is called overloading.

Methods Using Variable Arguments

A variation of method overloading is when you need a method that takes any number of arguments of the same type:

  • These three overloaded methods share the same functionality. It would be nice to collapse these methods into one method.

About Codingwelove

Recommended Posts × +


Post a Comment