【JAVA】11.方法

来源:互联网 发布:2017网络流行语翻译 编辑:程序博客网 时间:2024/06/14 16:16

一、JAVA的方法类似于其他语言的函数

二、定义方法

访问修饰符 返回值类型 方法名(形式参数列表){方法体}

· 访问修饰符:方法允许被访问的权限范围, 可以是 public、protected、private 甚至可以省略 。
【访问修饰符关键字:public、protected、private
用于控制程序中其他部分对这段代码的访问级别
public 所修饰的类,方法和变量是公共的,其他类可以访问该关键字修饰的类,方法和变量
protected 修饰方法和变量,可以被同一个包中的类或子类访问
private 修饰方法和变量,只能由所在类访问】
· 返回值类型:如果方法无返回值,则返回值类型指定为 void ;如果方法具有返回值,则需要指定返回值的类型,并且在方法体中使用 return 语句,终止方法运行并指定要返回的数据
· 方法名:定义的方法的名字,要使用合法的标识符
· 形式参数列表:传递给方法的参数列表,参数可以有多个,多个参数间以逗号隔开,每个参数由参数类型和参数名组成,由空格隔开 (实参:调用方法时实际传给方法的数据。实参的数目,数据类型和次序要和所调用方法声明的形参列表匹配)

三、根据方法是否带参、是否带返回值,可将方法分为四类

1、 无参无返回值方法

public void meth(){    System.out.println("hello");}

当需要调用方法执行某个操作时,可以先创建类的对象,然后通过对象名.方法名(); 来实现。

public class hello() {    public static void main(String[] args) {        hello text = new hello();//创建hello类的对象text        text.meth();//调用方法    }}

运行结果:hello

2、无参带返回值方法

public int meth(){//返回一个int型    int a = 5;    return a;//返回值为a(返回值最多只能有一个,不能返回多个值)}

调用:

public class hello() {    public static void main(String[] args) {        hello text = new hello();//创建hello类的对象text        int m = text.meth();//调用方法,m=a=5        System.out.println("m="+m);    }}

运行结果:m=5

3、带参无返回值方法

//调用public class hello() {    public static void main(String[] args) {        hello text = new hello();//创建hello类的对象text        text.meth(" world"," !");//调用方法,world,!为实参    }    //定义方法    public void meth(String n1,String n2){//n1,n2为形参        System.out.println("hello"+n1+n2);    }}

运行结果:hello world !

4、带参带返回值方法

public class hello() {    public static void main(String[] args) {        hello text = new hello();        String a = text.meth(" world");        System.out.println(a);    }    //定义方法    public String meth(String n){        return "hello"+n;    }}

运行结果:hello world

四、方法的重载
1、概念:如果同一个类中包含两个或两个以上方法名相同,但方法参数的个数、顺序或类型不同的方法,则称为方法的重载,也可称该方法被重载了。( 与方法的修饰符或返回值无关)
2、当调用被重载的方法时, Java 会根据参数的个数和类型来判断调用的是哪个方法,参数完全匹配的方法将被执行。
例:

public class hello() {    public static void main(String[] args) {        hello text = new hello();        text.meth(" world");//调用的是第一个方法    }    public void meth(String n){        System.out.println("hello"+n);    }    public void meth(String n1,String n2){        System.out.println("hello"+n1+n2);    }}

运行结果:hello world

0 0