Java的方法中一些问题

浅谈Java中的方法

static的作用

  1. 方法不带static
package com.wang.methodTest;

public class Demo01 {
    public static void main(String[] args) {
        Demo01 d = new Demo01();
        d.compare(1,3);
    }

    /*
    比大小,取大值
     */

    public  int compare(int a, int b){

        int result = 0;

        if (a == b){
            System.out.println("你输入的两个数相等");

        }else if(a > b){
            result = a;
            System.out.println(result);
        }else if (a < b){
            result = b;
            System.out.println(result);
        }
        return result;
    }
}

上面的compare方法没有加static,那么它从属于对象(实例方法),想要调用必须创建这个类的对象,通过对象来调用这个方法。具体实现可以参照上面的代码。

  1. 方法带static

    package com.wang.methodTest;
    public class Demo01 {
        public static void main(String[] args) {
            compare(1,3);
        }
    
        /*
        比大小,取大值
         */
    
        public static  int compare(int a, int b){
    
            int result = 0;
    
            if (a == b){
                System.out.println("你输入的两个数相等");
    
            }else if(a > b){
                result = a;
                System.out.println(result);
            }else if (a < b){
                result = b;
                System.out.println(result);
            }
            return result;
        }
    }
    
    

    上面加了static的话就属于类方法了,这样就可以直接调用,不需要通过对象来,具体实现看上面的代码。

方法的重载

在这里插入图片描述

什么是方法的重载呢?这个官方点说就是一个类中有相同的方法,方法名相同但是参数不同。那么很多人可能不是很理解,通俗说就是两个相同的东西,要区分的话就是内在的不同,真假美猴王一样。具体来段代码演示:

package com.wang.methodTest;



public class Demo01 {
    public static void main(String[] args) {
        compare(1,3);//3
        compare(1.1,2.3);//2.3
    }

    /*
    比大小,取大值
     */
    public static  double compare(double a, double b){

        double result = 0;

        if (a == b){
            System.out.println("你输入的两个数相等");

        }else if(a > b){
            result = a;
            System.out.println(result);
        }else if (a < b){
            result = b;
            System.out.println(result);
        }
        return result;
    }


    public static  int compare(int a, int b){

        int result = 0;

        if (a == b){
            System.out.println("你输入的两个数相等");

        }else if(a > b){
            result = a;
            System.out.println(result);
        }else if (a < b){
            result = b;
            System.out.println(result);
        }
        return result;
    }
}

可变参数

这个是接着上面提出的一个问题,有的时候我们根本就不能确定参数的个数的时候,无法进行方法的重载了,那么Java这个时候提供了一个很好的东西,就是可变参数

格式:参数类型... 参数名称 eg: int... m 注意点:只能放在最后

public static int amdddd(int a, int... m){
    
}

猜你喜欢

转载自blog.csdn.net/qq_39594037/article/details/107070461