Java 怎樣實現調用其他方法


Java主類的main方法調用其他方法

方法1: funA()方法設為靜態方法。 當主類加載到內存,funA()分配了入口地址,主要代碼如下:
public class test{  
     static void funA(){  
         System.out.println("we are students");  
     }  
    public static void main(String args[]){  
        System.out.println("Hello, 歡迎學習JAVA");  
        funA(); //使用靜態方法  
     }  
}
方法2: class A與 主類並列,如下
public class testDemo {
    /*
     * 成績統計
     * */
    public static void main(String[] args) {
        Integer[] chinaScore = {100,70,80,60,88};
        int count=0;
        //合計值
        for(int i = 0;i<chinaScore.length;i++) {
            count+=chinaScore[i];
        }
        System.out.println("總成績:"+count);
        
        //平均值
        int scoreAvg = count/chinaScore.length;
        System.out.println(scoreAvg);
        
        //保留2位小數
        DecimalFormat df = new DecimalFormat(".00");
        System.out.println(df.format(scoreAvg));
        
        //最大值
        
        int min = (int) Collections.min(Arrays.asList(chinaScore));
        int max = (int) Collections.max(Arrays.asList(chinaScore));
        System.out.println("歷史最高分:" + max);
        funA();//調用
        testClass otherFun = new testClass();//使用外部類
        otherFun.vo();
    }

    /*
     * 自定義funA()函數靜態方法
     * **/
    static void funA() {
        System.out.println("we are students");
    }
}

//class A與 主類並列,main方法中調用其他類的函數
class testClass{
    void vo() {
        System.out.println("你很帥");
    }
}
方法3:A a=new test().new A(); 內部類對象通過外部類的實例對象調用其內部類構造方法產生
public class test{  
     class A{  
           void fA(){  
               System.out.println("we are students");  
              }  
        }  
     public static void main(String args[]){  
        System.out.println("Hello, 歡迎學習JAVA");  
        A a=new test().new A();  //使用內部類  
        a.fA();     
        }  
}

 


免責聲明!

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



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