函數也被稱為方法!
函數的作用及特點:
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