java中的方法(method)到底怎么用?給個例子


7.方法(method)  


被調例子,

int add(int x, int y){
return x+y;
}

主調例子,
for example:
int result = add(5,3);

大家可以看出來和c語言是一樣的。

 

7.1 Variable Scope(變量范圍)

1)Class(類) scope
類中所有的方法都可以用
2)Block(塊) scope
只在他聲明的塊中有效 or 嵌套的塊兒中
3)Method(方法) scope
只在他聲明的方法中有效

下例中,i是類變量,k 是塊兒變量,j是方法變量,
public class Test{
    static int i = 10;
    public static void main(String[] args){
        int j = 20;
        int r = cube(i);
        System.out.println(r);
        r = cube(j);
        System.out.println(r);
        {   
            int k = 30;
            r = cube(k);
            System.out.println(r);
        }
    //r = cube(k);there is an error here.錯誤
    }
    static int cube(int n){
        return n*n*n;
    }
}

 

更多內容請見原文,原文轉載自:https://blog.csdn.net/qq_44639795/article/details/103145051


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM