【JAVA SE】8.方法

来源:互联网 发布:黑马程序员官网登录 编辑:程序博客网 时间:2024/06/04 17:54

一、方法

  • 定义在类中,具有特定功能的一段独立小程序
  • Java中的方法类似于C语言中的函数

二、定义方法

  • 格式:访问修饰符 返回值类型 方法名(形式参数列表){方法体}
  • 访问修饰符:【后面会介绍】
  • 返回值类型:如果方法无返回值,则返回值类型指定为 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();//调用方法    }}

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);    }}

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);    }}

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;    }}

四、方法的重载

  • 概念:如果同一个类中包含两个或两个以上方法名相同,但方法参数的个数、顺序或类型不同的方法,则称为方法的重载,也可称该方法被重载了。
  • 与方法的修饰符或返回值无关,只看参数列表。
void method(int x)int method(int y) 不是重载
  • 当调用被重载的方法时, 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);    }}
0 0
原创粉丝点击