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

2022/1/8 20:07:18

本文主要是介绍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){

    }
}



这篇关于java知识学习————方法重载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程