java知识学习————方法重载

方法

java中的方法可以理解为c语言中的函数

//这是一段java代码来求出输入的值哪个大
import java.util.Scanner;

public class max2 {
    public static void main(String[] args) {//主函数
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        int c = getMax(a,b);
        System.out.println(c);
    }
    public static int getMax(int a,int b){ //方法
        int max = 0;
        if(a>b){max = a;}else{max = b;}
        return max;
    }
}
#include<stdio.h>
//这是来求出a和b之间的最大值的函数
int getMax(int a,int b)
{
   if(a>b)
   {return a;}else{return b;}
}

int main()
{
   int a,b,max;
   scanf("%d",&a);
   scanf("%d",&b);
   max = getMax(a,b);
   printf("%d",max);
   return 0;
}

方法有许多地方和函数相似,例如形参和实参,以及方法和函数的调用,但也有不同首先一点就是方法可以重载,而相同函数名在一个c文件中无法多次定义

方法重载

方法重载指的是一个类(class)中的出现了两个及以上的相同方法名但是方法的定义不同的方法,和返回值和方法体的实现没有关系,接下来是方法重载的几种情况

/*
这种情况就会报错,就算是方法返回的值的类型不一样,但是其方法定义的参数数目以及类型都一样,则被认为是同
一个方法被写了两次
*/
public class test{
    public static void getMax(int a,int b,int c){//在test类中创建了一个getMax的方法
    }
    public static int getMax(int a,int b,int c){//创建了一个getMax方法
    }
}
/*
这种情况下就会正常运行,因为在同一个类中创建了两个相同方法名,但是定义的参数数量不一样,此时这两个方法是不同的方法,
但是共用一个方法名,在调用时候就需要注意参数的数量以及类型
*/
public class test{
    public static void getMax(int a,int b,int c){//在test类中创建了一个getMax的方法,其中有三个int型参数
    }
    public static void getMax(int b,int c){//创建了一个getMax方法,其中有两个int型参数
    }
}
/*
这种情况下就会正常运行,因为在同一个类中创建了两个相同方法名,但是定义的参数一样,但是类型不完全一样,
此时这两个方法是不同的方法,但是共用一个方法名,在调用时候就需要注意参数的数量以及类型
*/
public class test{
    public static void getMax(int a,int b,float c){//在test类中创建了一个getMax的方法,其中有两个个int型参数,一个float
    }
    public static void getMax(int b,int c,double c){//创建了一个getMax方法,其中有两个int型参数,一个float参数
    }
}
/*
这种情况下就会正常运行,因为在同一个类中创建了两个相同方法名,但是定义的参数个数一样,
类型也都是两个int和一个float,但是变量的顺序不一样,则会正常运行
*/
    public static int getMax(int a,float c,int b){

    }
    public  static int getMax(float a,int c,int b){

    }
/*
这种情况下就会正常运行,但它并不是方法重载,因为这是在两个不同的类中,就不符合方法重载的要求(在一个类中)
*/
public class class1{
     public static int getMax(int a,float c,int b){

    }
}

public class class2{
      public static int getMax(int a,float c,int b){

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂派爱丽丝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值