首页 > 编程 > Java > 正文

【JAVA】7.方法

2019-11-11 03:14:11
字体:
来源:转载
供稿:网友

一、方法

含义:定义在类中,具有特定功能的一段独立小程序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();//调用方法 }}

运行结果: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

四、方法的重载

概念:如果同一个类中包含两个或两个以上方法名相同,但方法参数的个数、顺序或类型不同的方法,则称为方法的重载,也可称该方法被重载了。与方法的修饰符或返回值无关,只看参数列表当调用被重载的方法时, 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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表