函数也被称为方法!
函数的作用及特点:
1、用于定义功能,将功能封装。
2、可以提高代码的复用性。
函数注意事项:
1、不能进行函数套用(不可以在函数内定义函数)。
2、函数只有被调用才能被执行。
3、基本数据类型(String、int、….)修饰的函数类型,要有return返回值。
4、void修饰的函数,函数中的return语句可以省略不写。
5、函数名可以根据需求进行命名。
代码示例:(有无函数/方法的区别)
无函数/方法代码例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class NoFunc {
public static void main(String[] args) { //main也是一个函数,用于程序运行
int a= 1 ;
int b= 2 ;
int addSum= 0 ;
int mulSum= 0 ;
addSum=a+b;
mulSum=a*b;
System.out.println( "加法" +addSum);
System.out.println( "乘法" +mulSum);
a= 2 ; //修改a值,另做运算
addSum=a+b;
mulSum=a*b;
System.out.println( "加法" +addSum);
System.out.println( "乘法" +mulSum);
}
}
|
普通函数/方法代码例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class Func {
int a= 1 ; //a为实际参数
int b= 2 ;
void Cal( int addSum, int mulSum){ //sum为形式参数
addSum=a+b;
mulSum=a*b;
System.out.println( "加法" +addSum);
System.out.println( "乘法" +mulSum);
//void无返回值
}
//修改a值,另做运算
int setA( int a){ //a为形式参数
this .a=a; //实际参数赋值给形式参数
return a; //return返回值a
}
public static void main(String[] args) { //main也是一个函数,用于程序运行
Func f= new Func(); //创建对象
f.Cal( 0 , 0 ); //对象调用Add函数,0赋值给sum(初始化)
f.setA( 2 ); //a赋值为2
f.Cal( 0 , 0 ); //另做运算
}
}
|
运行结果:(相同)
加法3
乘法2
加法4
乘法4
函数分类:
1、普通函数
2、构造函数
3、main函数(特殊)
构造函数注意事项:
1、构造函数的方法名必须与类名相同。
2、不能声明函数类型,没有返回类型,也不能定义为void。
3、不能有任何非访问性质的修饰符修饰,例如static、final、synchronized、abstract都不能修饰构造函数。
4、构造函数不能被直接调用,必须通过new关键字来调用。
构造函数的作用:
1、方便参数的传递。
2、 通过new调用构造函数初始化对象。是给与之格式(参数列表)相符合的对象初始化。
构造函数代码例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
public class Constructor {
int a= 233 ;
int b= 233 ;
Constructor(){
//无参构造函数
}
Constructor( int a, int b){ //有参构造函数
this .a=a;
this .b=b;
}
void Cal(){
int addSum=a+b;
int mulSum=a*b;
System.out.println( "加法" +addSum);
System.out.println( "乘法" +mulSum);
//void无返回值
}
//修改a值,另做运算
int setA( int a){ //a为形式参数
this .a=a; //实际参数赋值给形式参数
return a; //return返回值a
}
public static void main(String[] args) {
Constructor c1= new Constructor(); //无参构造函数创建的对象
c1.Cal(); //无参构造函数对象调用Cal函数
Constructor c2= new Constructor( 1 , 2 ); //对象初始化
c2.Cal(); //有参构造函数对象调用Cal函数
c2.setA( 2 ); //a赋值为2
c2.Cal(); //另做运算
}
}
|
运行结果:
加法466
乘法54289
加法3
乘法2
加法4
乘法4
原文链接:https://www.idaobin.com/archives/396.html