Arvutiteaduse instituut
  1. Kursused
  2. 2017/18 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (P2NC.01.083)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2017/18 kevad

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
Session 2

Overloading of methods

Quite often we want to create slight variations of the same method with different parameters. For example, we might have a method multiplyNumbers that allows us to find the multiplication of two numbers:

 multiplyNumbers(4,5);

and other times we want to find the square of the number:

 multiplyNumbers(4);

Some programming languages require to come up with different names for the methods (e.g. multiplyNumbers and squareNumber). Fortunately Java allows us to have more than one method with the same name as long as they have different parameters. This process is called overloading. The primary requirement for overloading: the different methods have different method signatures.

The signature of a method is the name of the method and the data types of its parameters. Example:

 myMethod( int, double, String )

Note! The modifier and the return type are not part of the signature. Either the names of the parameters matter!

Example of method multiplyNumbers overloading (pay attention to the signatures!):

public class MultiplyNumbers{

    public static int multiplyNumbers(int a, int b){
        return a*b;
    }

    public static int multiplyNumbers(int a){
        return a*a;
    }

    public static void main(String[] args){
        System.out.println(multiplyNumbers(3,5));

        System.out.println(multiplyNumbers(5));

    }
}

Self-assessment

Session 2
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused