Przejdź do głównej zawartości

Method Overloading - Java baisics

Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists.

The same method name but different number of parameters.

public class Main {

    public static void main(String[] args) {
        // no return value
        calculateScore("Pawel",100);
        //we use returned variable score and put to the new variable
        int newScore = calculateScore("John",100);
        System.out.println("New score is "+ newScore);

        //results of method overloading
        calculateScore(100);

        // result of method overloading

        calculateScore();

        // data type of return variable does not overload method
    }
    public static int calculateScore (String playerName, int score){
        System.out.println("Player " + playerName +" scored "+score + " points");
        return score*1000;
    }
    // method overloading
    public static int calculateScore (int score){
        System.out.println("Unnamed Player scored "+score + " points");
        return score*1000;
    }
    // method overloading
    public static int calculateScore (){
        System.out.println("Unnamed Player no player score");
        return 0;
    }
}

  • Example 1: Overloading – Different Number of parameters in argument list
  • Example 2: Overloading – Difference in data type of parameters
  • Example 3: Overloading – Sequence of data type of arguments

Komentarze

Popularne posty z tego bloga

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if

String-1 > endsLy

Given a string, return true if it ends in "ly". endsLy("oddly") → true endsLy("y") → false endsLy("oddy") → false public boolean endsLy ( String str ) { if ( str . length ()< 2 ){ return false ; } if (( str . substring ( str . length ()- 2 , str . length ())). equals ( "ly" )){ return true ; } return false ; }

String-1 > withouEnd2

Given a string, return a version without both the first and last char of the string. The string may be any length, including 0. withouEnd2("Hello") → "ell" withouEnd2("abc") → "b" withouEnd2("ab") → "" public String withouEnd2 ( String str ) { if ( str . length ()== 1 ){ return str . substring ( 1 ); } else if ( str . length ()== 0 ){ return str ; } return ( str . substring ( 1 , str . length ()- 1 )); }