Computer Science
Java Method Overloading
Java Method Overloading is a feature that allows a class to have multiple methods with the same name but different parameters. This enables the programmer to reuse the same method name and provide different functionality based on the type and number of arguments passed to the method. Method overloading is a form of polymorphism in Java.
Written by Perlego with AI-assistance
Related key terms
1 of 5
6 Key excerpts on "Java Method Overloading"
- eBook - PDF
Data Structures
Abstraction and Design Using Java
- Elliot B. Koffman, Paul A. T. Wolfgang(Authors)
- 2021(Publication Date)
- Wiley(Publisher)
1.3 Method Overriding, Method Overloading, and Polymorphism 17 Polymorphism An important advantage of OOP is that it supports a feature called polymorphism, which means many forms or many shapes. Polymorphism enables the JVM to determine at run time which of the classes in a hierarchy is referenced by a superclass variable or parameter. Next, we will see how this simplifies the programming process. Suppose you are not sure whether a computer referenced in a program will be a notebook or a regular computer. If you declare the reference variable Computer theComputer; you can use it to reference an object of either type because a type Notebook object can be referenced by a type Computer variable. In Java, a variable of a superclass type (general) can reference an object of a subclass type (specific). Notebook objects are Computer objects with more features. When the following statements are executed, theComputer = new Computer("Acme", "Intel", 2, 160, 2.6); System.out.println(theComputer.toString()); you would see four output lines, representing the state of the object referenced by theComputer. Now suppose you have purchased a notebook computer instead. What happens when the following statements are executed? theComputer = new Notebook("Bravo", "Intel", 4, 240, 2.4. 15.0, 7.5); System.out.println(theComputer.toString()); Recall that theComputer is type Computer. Will the theComputer.toString() method call return a string with all seven data fields or just the five data fields defined for a Computer object? The answer is a string with all seven data fields. The reason is that the type of the object receiving the toString message determines which toString method is called. Even though variable theComputer is type Computer, it references a type Notebook object, and the Notebook object receives the toString message. Therefore, the method toString for class Notebook is the one called. - No longer available |Learn more
Java Fundamentals
A fast-paced and pragmatic introduction to one of the world's most popular programming languages
- Gazihan Alankus, Rogério Theodoro de Brito, Basheer Ahamed Fazal, Vinicius Isola, Miles Obare(Authors)
- 2019(Publication Date)
- Packt Publishing(Publisher)
Student class:public class Student extends Person { …. public void walk(int speed){ //Walk to class System.out.println("Walking to class .."); } …... }When we call student.walk(20) , this method in our Student class will be called instead of the same method in the Person class. That is, we have provided a unique way to walk for our Student class that isn't the same for the Lecturer and Person classes.In Java, we refer to such a method as overridden and the process as method overriding. The Java virtual machine (JVM) calls the appropriate method for the object that is referred.The Difference between Overriding and Overloading
Let's have a look at the difference between method overloading and overriding:- Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments:void foo(int a) void foo(int a, float b)
- Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another would exist in the child class:class Parent { void foo(double d) { // do something } } class Child extends Parent { void foo(double d){ // this method is overridden. } }
Annotations
We will now cover another important topic that will help us write better Java programs.Annotations are a way in which we can add metadata to our programs. This metadata can include information such as the version of a class we are developing. This is useful in scenarios where a class is deprecated or where we are overriding a certain method. Such metadata is not part of the program itself, but can help us catch errors or offer guidance. Annotations have no direct effect on the operation of the code they annotate.Let's look at a scenario. How do we ensure that we are overriding a certain method and not creating another completely different method? When overriding a method, a single mistake such as using a different return type will cause the method to not be overridden anymore. Such a mistake is easy to make but can lead to software bugs later on if not taken care of early in the software development stages. How, then, do we enforce overriding? The answer, as you might have already guessed, is using annotations. - Joyce Farrell(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
Parameter lists differ when the number and order of types within the lists are unique. For example, you could write several methods with the same identifier, and one method could accept an int , another two int s, and another three int s. A fourth method could accept an int followed by a double , and another could accept a double followed by an int . Yet another version could accept no parameters. The parameter identifiers in overloaded methods do not matter, nor do the return types of the methods. The only two requirements to overload methods are the same identifier and different parameter lists. Instead of overloading methods, you can choose to use methods with different names to accept the diverse data types, and you can place a decision within your program to determine which version of the method to call. However, it is more convenient to use one method name and then let the compiler determine which method to use. Overloading a method also makes it more convenient for other programmers to use your method in the future. Usually you do not create overloaded methods so that a single program can use all the versions. More often, you create overloaded methods so different programs can use the version most appropriate to the task at hand. Frequently, you create overloaded methods in your classes not because you need them immediately, but because you know client programs might need multiple versions in the future, and it is easier for programmers to remember one reasonable name for tasks that are functionally identical except for parameter types. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience.- Joyce Farrell(Author)
- 2012(Publication Date)
- Cengage Learning EMEA(Publisher)
The interface is the part that a client sees and uses. A method ’ s client is a program or other method that uses the method. A method ’ s return type is the data type for any value it returns. A void method returns no value. A method ’ s type is its return type. A method declaration is composed of the method ’ s return type and signature. Overloading involves supplying diverse meanings for a single identifier. To overload a method is to write multiple methods with a shared name but different parameter lists. Polymorphism is the ability of a method to act appropriately according to the context. Ambiguous methods are overloaded methods for which the compiler cannot determine which version to use. Review Questions 1. Which of the following is true? a. A class can contain two methods at most. b. A class might contain a method that calls two other methods. c. A method might contain two or more other methods. d. All of the above are true. 2. Which of the following must every method have? a. a header b. a parameter list c. at least one local variable d. all of the above 3. Which of the following is most closely related to the concept of local ? a. abstract b. object-oriented c. in scope d. class level 242 C H A P T E R 6 Using Methods Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 4. Although the terms parameter and argument are closely related, the difference between them is that argument refers to . a. a passed constant b. a value in a method call c. a formal parameter d.- eBook - ePub
Learning Java by Building Android Games
Learn Java and Android from scratch by building five exciting games, 3rd Edition
- John Horton(Author)
- 2021(Publication Date)
- Packt Publishing(Publisher)
already defined error:Figure 4.5 – Error due to methods with the same name and same parameters Remove the offending method; we will write some code so that we can see the methods in action shortly.Now, insert this code just before the closing } of the onCreate method to call the methods and print some values to the logcat window:// Declare and initialize a String and an int int anInt = 10; String aString = "I am a string"; // Now call the different versions of printStuff // The name stays the same, only the parameters vary printStuff(anInt); printStuff(aString); printStuff(anInt, aString);Running the method overloading mini-app
Now, we can run the app on the emulator or a real device. Nothing will appear on the emulator screen, but here is the logcat output: info : This is the int only version info : myInt = 10 info : This is the String only version info : myString = I am a string info : This is the combined int and String version info : myInt = 10 info : myString = I am a stringAs you can see, Java has treated three methods with the same name as different methods. This, as we have just proved, can be useful. As a reminder, this is called method overloading .Method overloading and overriding confusionOverloading is when we have more than one method with the same name but different parameters.Overriding is when we replace a method with the same name and the same parameter list, as we have done with onCreate . Note that when you override, you also have the option to call the overridden version of the method, as we did with onCreate using super.onCreate() .We know enough about overloading and overriding to complete this book; however, if you are brave and your mind is wandering, know that yes, you can override an overloaded method, but that is something for another time.How it works
This is how the code works. In each of the steps where we wrote code, we created a method called printStuff . But each printStuff - eBook - PDF
- Joyce Farrell(Author)
- 2018(Publication Date)
- Cengage Learning EMEA(Publisher)
A program containing a potentially ambiguous situation will run problem-free if you do not make any ambiguous method calls. It is important to remember that you can overload methods correctly by providing different parameter lists for methods with the same name. Methods with identical names that have identical parameter lists but different return types are not overloaded—they are illegal. For example, the following two methods are illegal in the same class: int aMethod(int x) void aMethod(int x) The compiler determines which of several versions of a method to call based on the arguments in the method call, and does not consider the return type. Watch the video Overloading Methods. The compiler determines which version of a method to call by the method’s signature. In Chapter 3, you learned that a method’s signature is the combination of the method name and the number, types, and order of parameters. If the keyword final appears in a method’s parameter list, it is ignored when determining ambiguity. In other words, two methods with the headers void aMethod(int x) and void aMethod(final int x) are ambiguous. Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 187 Creating and Calling Constructors with Parameters Creating and Calling Constructors with Parameters In Chapter 3, you learned that Java automatically provides a constructor when you create a class. You also learned that you can write your own constructor, and that you often do so when you want to ensure that fields within classes are initialized to some appropriate default value.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.





