Java基础学习(一)—方法

一、方法的定义及格式

定义: 方法就是完成特定功能的代码块。

格式:

 修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2){	
 	函数体;
	return 返回值;
}

范例1: 写一个两个数求和的方法

public class MethodDemo1{

	public static void main(String[] args){
		
		int c = sum(10,10);
		System.out.println(" c = " + c);
	}
	
	/*
	 * 求和的方法
	 */
	public static int sum(int a,int b){
		return a + b;
	}
}

范例2:写一个三个数求最大值的方法

public class MethodDemo1{

	public static void main(String[] args){
		
		int x = 5;
		int y = 10;
		int z = 15;
		
		System.out.println("Max = " + getMax(x,y,z));	
	}
	
	/*
	 * 求三个数的最大值
	 */
	public static  int getMax(int a,int b,int c){
		int temp = a > b ? a : b;
		int max = temp > c ? temp : c;
		return max;
	}
}

 

二、方法的重载

1.概述

    在同一个类中,允许多个同名的方法,只要它们的参数个数或者参数类型不同即可。

 

2.特点

     (1)方法的重载与返回值无关,只看方法名和参数列表。

     (2)在调用时,虚拟机通过参数列表的不同来区分同名方法。

 

范例: 求和方法的重载

public class MethodDemo1{

	public static void main(String[] args){
		
		int x = 5;
		int y = 10;
		
		System.out.println("sum = " + sum(x,y));
	}
	
	/*
	 * 下面两个方法是重载
	 */
	public static  int sum(int a,int b){
		return a + b;
	}
	
	public static int sum(int a,int b,int c){
		return a + b + c;
	}
}
posted @ 2016-04-14 10:18  ✈✈✈  阅读(202)  评论(0编辑  收藏  举报