java中方法的重载

本主要讲述java中方法的重载

方法包括:修饰符,返回类型,方法名称,形参列表

重载:方法名相同,形参列表不同(形参的个数,形参的数据类型,形参的顺序至少有一个不同)

示例代码如下:

public class OverLoadTest {
    public static void main(String[] args) {
        T t = new T();
        t.method(3);
        t.method(4,4);
        t.method("hello 老师");
        
        double res1 = t.max(4, 5, 6.0);
        double res2 = t.max(4,5,6);
        
        System.out.println("res1="+res1+",res2="+res2);
    }

}

class T {
    
    public int max(int n1,int n2) {
        return n1 > n2 ? n1 : n2;
    }
    
    public double max(double n1,double n2) {
        return n1 > n2 ? n1:n2;
    }
    
    public double max(double n1,double n2,double n3) {
        System.out.println("执行了max(double n1,double n2,double n3)");
        double max1 = n1 > n2 ? n1:n2;
        return max1 > n3 ? max1:n3;
    }
    
    public double max(double n1,double n2,int n3) {
        System.out.println("执行了max(double n1,double n2,int n3)");
        double max1 = n1 > n2?n1:n2;
        return max1 > n3?max1:n3;
    }
}

这里的max就构成了重载,形参列表的数据类型不同,形参列表的个数不同。

 

注意:方法重载与返回类型无关,如上图所示,返回类型不同,仍视为同一个方法。

 

posted @ 2022-12-09 22:03  zwGitOne  阅读(269)  评论(0)    收藏  举报