Java-5 Java中方法定义

1.Java的方法

  • 比如友谊程序,运行过程中每次运行都需要重复编写这段代码,这样会使代码变得很臃肿,重复的代码会很多,为了解决代码重复编写问题,可以将获取最值的代码提取出来放大一个大括号中,并为这段代码起个名字,这样在每次获取最值的地方通过这个名字来调用获取最值的代码就可以了。

  • 方法定义格式

    修饰符 返回值类型 方法名(参数列表){
    	方法体;
    }
    修饰符: public static
    
    没有返回值方法: void
    有返回值的方法: 数据类型
    
    方法名: 小驼峰命名法
    
    方法体:要实现功能
    
    方法的调用: 方法名(参数)
    
  • demo

    package func;
    
    public class FuncDemo1 {
    	public static void main(String[] args) {
    		demo();
    	}
        // 不带参数
    	public static void demo() {
    		System.out.println("demo");
    	}
        // 带参数
        public static void demo2(int a) {
    		System.out.println("demo" + a);
    	}
    }
    
  • 定义个方法:打印2个数的和

    public static void sum(int x, int y) {
    		System.out.println(x + y);
    }
    
  • 有返回值方法:

    package func;
    
    public class FuncDemo1 {
    	public static void main(String[] args) {
    		double a1 = printAreaCircle(3);
    		System.out.println(a1);
    	}
        // 返回 double类型. 传入double类型数据
    	public static double printAreaCircle(double r) {
    		double area = 3.14*r*r;
    		return area;
    	}
    }
    
  • 判断一个数是不是偶数

    package func;
    
    public class FuncDemo2 {
    	public static void main(String[] args) {
    		boolean result = isEven(22);
    		System.out.println(result);
    	}
    	public static boolean isEven(int a) {
    		if (a%2==0) {
    			return true;
    		}
    		return false;
    	}
    }
    // true
    
  • 求三个数最大值

    package func;
    
    public class FuncDemo2 {
    		float maxNum = getMax(12.4f,14,14.5f);
    		System.out.println(maxNum);// 14.5
    	}
        public static float getMax(float a, float b, float c) {
            return a>b?a>c?a:c:b>c?b:c;
        }
    }
    
  • 方法的重载

    • 一个类中可以存在多个名字相同的方法,但是要必须保证参数的个数或类型不同,与返回值无关。
    package func;
    
    public class FuncDemo3 {
    	public static void main(String[] args) {
    		int res1 = getSum(1,3);
    		int res2 = getSum(1,2,4);
    		System.out.println(res1);// 4
    		System.out.println(res2);// 7
    	}
    	
    	public static int getSum(int a, int b) {
    		return a + b;
    	}
    	public static int getSum(int a, int b, int c) {
    		return a + b + c;
    	}
    }
    
原文地址:https://www.cnblogs.com/xujunkai/p/13698040.html