Wednesday, January 1, 2020

What Is Overloading in Java

Overloading in Java is the ability to define more than one method with the same name in a class. The compiler is able to distinguish between the methods because of their method signatures. This term also goes by  method overloading, and is mainly used to just increase the readability of the program; to make it look better. However, do it too much and the reverse effect may come into play because the code looks  too  similar, and can be hard to read. Examples of Java Overloading There are nine different ways the print method of the System.out object can be used: When you use the print method in your code, the compiler will determine which method you want to call by looking at the method signature. For example: A different print method is being called each time because the parameter type being passed is different. Its useful because the print method will need to vary how it works depending on whether it has to deal with a string, integer, or boolean. More Information on Overloading Something to remember about overloading is that you cant have more than one method with the same name, number, and type of argument because that declaration doesnt let the compiler understand how theyre different. Also, you cant declare two methods as having identical signatures, even if they have unique return types. This is because the compiler doesnt consider return types when differentiating between methods. Overloading in Java creates consistency in the code, which helps eliminate  inconsistencies, which could lead to syntax errors. Overloading is also just a convenient way to make the code easier to read through.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.