day05

来源:互联网 发布:日语中文同声翻译软件 编辑:程序博客网 时间:2024/05/16 14:41

方法

1.方法的概述方法有什么好处?      我们之前没有方法,所有代码只执行一次,不能重复执行. 我们写方法,就可以多次使用同一段代码.格式:    修饰符 返回值类型  方法名(参数类型 参数值,参数类型1 参数值1...){        方法体;        return 返回值;    }2.方法的定义和方法的调用    1)方法的定义:    需求:定义一个方法,求两个数的和    public static int getSum(int a,int b){        int c = a + b;        return c;  //把c返回给调用者    }    2)方法的调用    格式:方法名(实际的参数1,实际参数2...)    int c = getSum(10,20);

方法的重载

 1.什么是方法的重载:  在同一个类中,出现同名的方法,参数列表不同,与返回值无关. 重载的情况:        1) 参数列表的个数不同        public static void fun(int a , int b){}        public static void fun(int a ){}        2)参数的数据类型不同        public static void fun(int a , int b){}        public static void fun(int a ,float f){}        3)参数的顺序不同        public static void fun(float a , int b){}        public static void fun(int a ,float f){}

2.练习1

    定义重载的两个方法实现比较两个数据是否相等。    要求:    1.第一个方法的参数类型为两个int类型    2.第二个方法的参数类型为两个double类型    3.在main方法中进行测试     参考:     /*     * 定义重载的两个方法实现比较两个数据是否相等。            要求:            1.第一个方法的参数类型为两个int类型            2.第二个方法的参数类型为两个double类型            3.在main方法中进行测试     */    public class Test3 {        public static void main(String[] args) {    //      boolean b = method(2,2);    //      System.out.println(b);            //boolean b = method(2.2,2.2);            boolean b = method(2,2);            System.out.println(b);        }        public static boolean method(int a , int b){            System.out.println("第一个方法");            if(a == b){                return true;            }else{                return false;            }        }        public static boolean method(double d, double e){            System.out.println("第二个方法");            if(d == e){                return true;            }else{                return false;            }        }    }

3.基本数据类型作为参数

    结论:基本数据类型作为形式参数时,不影响实际参数的值    举例:    /*     * 基本数据类型作为形式参数时,不影响实际参数的值     */    public class Test4 {        public static void main(String[] args) {            int a = 10;            int b =20;            method(a,b);            System.out.println(a);  // 10 还是20?            System.out.println(b);  // 20 还是30?        }        public static void method(int a, int b) {            a = a + 10; //20            b = b + 10; //30        }    }

4.引用数据类型作为形式参数

    结论: 引用数据类型作为形式参数,直接影响实际参数的值.
0 0
原创粉丝点击