Java-重载-方法

时间:2020-02-23 14:36:44  来源:igfitidea点击:

在本教程中,我们将学习Java编程语言中的方法重载。

Java中方法的重载是什么?

在Java中,当多个方法共享相同的名称但参数声明不同时,则称这些方法被重载,并且该过程称为方法重载。

语法

class NameOfTheClass {
  
  access_modifier return_type methodName(list_of_params_1) {
    //some code...
  }

  access_modifier return_type methodName(list_of_params_2) {
    //some code...
  }
}

其中,NameOfTheClass是类的名称,它具有两个共享相同名称methodName的方法,但它们具有不同的参数声明。

范例1:

在下面的示例中,我们的Compute类具有重载的Area方法。

如果我们将单个参数传递给该方法,那么我们正在计算一个正方形的面积。
如果我们传递两个参数,那么我们正在计算矩形的面积。

class Compute {

  //this method will compute the area of a square
  public double area(double side) {
    return side * side;
  }

  //this method will compute the area of a rectangle
  public double area(double length, double breadth) {
    return length * breadth;
  }
}

class MethodOverloadingExample {
  public static void main(String[] args) {
    //create object
    Compute obj = new Compute();

    //variable
    double area, side, length, breadth;

    //find the area of a square
    side = 12.5;
    area = obj.area(side);
    System.out.println("Area of square having side " + side + " is " + area);

    //find the area of a rectangle
    length = 10.6;
    breadth = 20;
    area = obj.area(length, breadth);
    System.out.println("Area of rectangle having length " + length + " and breadth " + breadth + " is " + area);
  }
}
$javac MethodOverloadingExample.java 
$java MethodOverloadingExample
Area of square having side 12.5 is 156.25
Area of rectangle having length 10.6 and breadth 20.0 is 212.0

范例2:

在下面的示例中,我们将创建一个具有isHappy方法被重载的Happy类。

第一种方法是:

public void isHappy(boolean happy) {
}

它以布尔值作为参数,并根据参数值打印输出消息。

第二种方法是:

public boolean isHappy(int happinessLevel) {
}

这需要一个整数参数,并根据该值将布尔值返回给调用方法。
然后,我们可以使用返回值和一些合适的输出消息。

class Happy {

  //this method will print the output based on boolean value passed
  public void isHappy(boolean happy) {
    if (happy == true) {
      System.out.println("Person is happy :)");
    } else {
      System.out.println("Person is sad :(");
    }
  }

  //this method will return boolean value
  public boolean isHappy(int happinessLevel) {
    if (happinessLevel > 5) {
      return true;
    } else {
      return false;
    }
  }
}

class MethodOverloadingExample {
  public static void main(String[] args) {
    //create object
    Happy person = new Happy();

    //passing boolean value and printing result
    System.out.println("Is person happy? ");
    person.isHappy(true);

    //passing integer value and getting back boolean value
    int happinessLevel = 5;
    boolean isPersonHappy = person.isHappy(happinessLevel);

    //now using the isPersonHappy boolean value and calling the method
    System.out.println("Happiness Level " + happinessLevel);
    person.isHappy(isPersonHappy);
  }
}
$javac MethodOverloadingExample.java 
$java MethodOverloadingExample
Is person happy? 
Person is happy :)
Happiness Level 5
Person is sad :(