Methods in java method overloading in java

Method Overloading in Java with Examples

Method overloading in java is a feature that allows a class to have more than one method with the same name, but with different parameters.

Java supports method overloading through two mechanisms:

  1. By changing the number of parameters
  2. By changing the data type of parameters Overloading by changing the number of parameters A method can be overloaded by changing the number of parameters.
  • What is Method overloading in java?
  • Benefits of Using Method Overloading
  • How to do Method Overloading?
Читайте также:  Python with open seek

What is Method overloading in Java?

“Method overloading is a feature of Java in which a class has more than one method of the same name and their parameters are different.”

In other words, we can say that Method overloading is a concept of Java in which we can create multiple methods of the same name in the same class, and all methods work in different ways. When more than one method of the same name is created in a Class, this type of method is called the Overloaded Method. Before moving ahead, if you wish to brush up your Java skills, you can take up a Java programming for beginners that will help you learn the foundations.

Must Learn Java Concepts

We can easily understand about method of overloading by the below example:

Suppose we have to write a method to find the square of an integer number. We can write this method as follows:

public void intSquare ( int number )

Suppose we want to find the square of 10, then to find the square of 10, we can call this method as follows:

Now, if we want to find the Square of a double type value, then we have to create another Square () method as follows:

public void doubleSquare(double number)

Similarly, if we want to find the square of long type value, then we have to create another method as follows:

public void longSquare(long number)

If we look carefully, to find the square of a number only, according to the data type of the number, we have to take three names as follows:

If it is possible that a programmer has to take only one name and the program itself decides which method to use for which type of value, then it will be easier for the programmer to get the same. There is no need to memorise the names of more than one method for type work. In Java, we can give the above three methods the same name.

If we provide only the square () name instead of giving different names to the above three methods and write the rest of the description as follows, then Java’s Compiler does not generate any error.

public void Square ( int number ) < int square = number * number; System.out.printIn(“Method with Integer Argument Called:“+square); >public void Square(double number) < double square = number * number; System.out.printIn(“Method with double Argument Called:“+square); >public void Square(long number)

If we define these three methods in a class, then these methods can be called Overloaded Methods as they have the same name. Let us develop CalculateSquare Class to understand this, which is as follows:

class CalculateSquare < public void square() < System.out.println("No Parameter Method Called"); >public int square( int number ) < int square = number * number; System.out.println("Method with Integer Argument Called:"+square); >public float square( float number ) < float square = number * number; System.out.println("Method with float Argument Called:"+square); >public static void main(String[] args) < CalculateSquare obj = new CalculateSquare(); obj.square(); obj.square(5); obj.square(2.5); >>

Note: We have not provided any argument in the ‘parenthesis’ of the square() method in our program. In this case, the Compiler Class calls the method in which no Parameter has been defined to achieve the Argument.

No Parameter Method Called

Method with Integer Argument Called: 25

Method with float Argument Called: 6.25

In this way, we can define more than one Methods of the same name in a class, which is called Method Overloading, and

The Java compiler itself performs the appropriate Method Call for an object, based on the Data Type of the Arguments of the Methods.

Benefits of using Method Overloading

  • Method overloading increases the readability of the program.
  • This provides flexibility to programmers so that they can call the same method for different types of data.
  • This makes the code look clean.
  • This reduces the execution time because the binding is done in compilation time itself.
  • Method overloading minimises the complexity of the code.
  • With this, we can use the code again, which saves memory.

How to do Method Overloading?

In java, we do method overloading in two ways:

  1. By changing the number of parameters.
  2. By changing data types.
  • Change the number of arguments:

In the example below, we have two methods, the first method has two arguments, and the second method has three arguments.

class Demo < void multiply(int a, int b) < System.out.printIn("Result is"+(a*b)) ; >void multiply(int a, int b,int c) < System.out.printIn("Result is"+(a*b*c)); >public static void main(String[] args) < Demo obj = new Demo(); obj.multiply(8,5); obj.multiply(4,6,2); >>

In the example given below, we have two methods, and their data types are different.

class Sum < static int add(int a, int b) < return a+b; >static double add(double a, double b) < return a+b; >> class TestOverloading2 < public static void main(String[] args) < System.out.println(Sum.add(17,13)); System.out.println(Sum.add(10.4,10.6)); >>

Note: In this example, we are creating static methods so that we don’t need to create an instance for calling methods.

Some points to remember about method overloading:

  • Method overloading cannot be done by changing the return type of methods.
  • The most important rule of method overloading is that two overloaded methods must have different parameters.

Method overloading has nothing to do with return-type.

If there are two methods of the same signature within a class in the program, then Ambiguity Error comes, whether their return-type is different or not. This means that method overloading has no relation with return-type.

class Sample < int disp(int x)< return x; >double disp(int y) < return y; >public static void main(String args[]) < Sample s = new Sample(); System.out.printIn("Value of x : " + s.disp(5)); System.out.printIn("Value of y : " + s.disp(6.5)); >> 

Sample.java:6: error: method disp(int) is already defined in class Sample

In this way, we can define more than one Methods of the same name in a class called Method Overloading. The Java Compiler itself, based on the Data Type of the Arguments of the Methods, performs the appropriate method call for an object.

This brings us to the end of the blog on Method Overloading in Java. Hope this helps you to up-skill your C++ skills. To learn more about programming and other related concepts, check out the courses on Great Learning Academy.

Also, if you are preparing for Interviews, check out these Interview Questions for Java to ace it like a pro.

Great Learning’s Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You’ll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Источник

Defining Methods

The only required elements of a method declaration are the method’s return type, name, a pair of parentheses, () , and a body between braces, <> .

More generally, method declarations have six components, in order:

  1. Modifiers—such as public , private , and others you will learn about later.
  2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name—the rules for field names apply to method names as well, but the convention is a little different.
  4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, () . If there are no parameters, you must use empty parentheses.
  5. An exception list—to be discussed later.
  6. The method body, enclosed between braces—the method’s code, including the declaration of local variables, goes here.

Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.

Definition: Two of the components of a method declaration comprise the method signature—the method’s name and the parameter types.

The signature of the method declared above is:

calculateAnswer(double, int, double, double)

Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:

run runFast getBackground getFinalData compareTo setX isEmpty

Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.

Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled «Interfaces and Inheritance»).

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString , drawInteger , drawFloat , and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw , each of which has a different parameter list.

public class DataArtist < . public void draw(String s) < . >public void draw(int i) < . >public void draw(double f) < . >public void draw(int i, double f) < . >>

Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

Источник

Methods in java method overloading in java

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don’t need to create instance for calling methods.

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.

Q) Why Method Overloading is not possible by changing the return type of method only?

In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let’s see how ambiguity may occur:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the same method having same parameters.

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let’s see the simple example:

Method Overloading and Type Promotion

One type is promoted to another implicitly if no matching datatype is found. Let’s understand the concept by the figure given below:

Java Method Overloading with Type Promotion

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int,long,float or double and so on.

Example of Method Overloading with TypePromotion

Example of Method Overloading with Type Promotion if matching found

If there are matching type arguments in the method, type promotion is not performed.

Output:int arg method invoked

Example of Method Overloading with Type Promotion in case of ambiguity

If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.

One type is not de-promoted implicitly for example double cannot be depromoted to any type implicitly.

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью