Java tut 18 : Kết hợp method Java ( Method phần 3) 0 (0)

Java tut 18 : Kết hợp method Java ( Method phần 3) 0 (0)

Java tut 18 : Kết hợp method Java ( Method phần 3) 0 (0)

Learn more »

Kết hợp method Java


Quá tải phương thức

Với tính năng nạp chồng phương thức , nhiều phương thức có thể có cùng tên với các tham số khác nhau:

Thí dụ

int myMethod(int x) float myMethod(float x) double myMethod(double x, double y) 

Hãy xem xét ví dụ sau, có hai phương pháp để thêm các số thuộc loại khác nhau:

Thí dụ

static int plusMethodInt(int x, int y) {   return x + y; }  static double plusMethodDouble(double x, double y) {   return x + y; }  public static void main(String[] args) {   int myNum1 = plusMethodInt(8, 5);   double myNum2 = plusMethodDouble(4.3, 6.26);   System.out.println("int: " + myNum1);   System.out.println("double: " + myNum2); } 

Hãy tự mình thử »

Thay vì xác định hai phương thức sẽ làm cùng một việc, tốt hơn là bạn nên nạp chồng cho một phương thức.

Trong ví dụ bên dưới, chúng tôi nạp chồng plusMethod phương thức để hoạt động cho cả int và double:

Thí dụ

static int plusMethod(int x, int y) {   return x + y; }  static double plusMethod(double x, double y) {   return x + y; }  public static void main(String[] args) {   int myNum1 = plusMethod(8, 5);   double myNum2 = plusMethod(4.3, 6.26);   System.out.println("int: " + myNum1);   System.out.println("double: " + myNum2); }         

Hãy tự mình thử »

Lưu ý: Nhiều phương thức có thể có cùng tên miễn là số lượng và / hoặc loại tham số khác nhau.


Lượt xem : 243

Integrations
Users

Share Profile

Anyone at KeenThemes can view
Anyone with link can edit

Give Award

Anyone at KeenThemes can view
Anyone with link can edit

Report User

Let us know why you’re reporing this person
Don't worry, your report is completely anonymous; the person you're
reporting will not be informed that you've submitted it