1. 程式人生 > 實用技巧 >回顧方法和方法呼叫及加深

回顧方法和方法呼叫及加深

回顧方法及加深

  • 方法的定義

    • 修飾符
    • 返回型別
    //Demo01    類
    public class Demo01 {
    
        //main  方法
        public static void main(String[] args) {
    
        }
    
        /*
          修飾符   返回值型別   方法名(...){
              //方法名
              return 返回值;
         */
        //return 結束方法,返回一個結果!
        public static String sayHello(){
            return "hello,world";
        }
    
        public void hello(){
            return;
        }
    
        public int max(int a,int b ){
            return a>b ? a : b; //三元運算子!
    
        }
    
        //陣列下標越界:Arrayindexoutofbounds
    
        public void readFile(String file) throws IOException{
    
        }
    }
    
    • break :跳出switch,結束迴圈和return的區別
    • 方法名:注意規範就OK 見名知意
    • 引數列表:(引數型別,引數名)...
    • 異常丟擲:疑問,後面講解
  • 方法的呼叫:遞迴

    • 靜態方法
    • 非靜態方法
    public class Demo02 {
        //靜態方法   static
    
        public static void main(String[] args) {
            //例項化這個類 new
            //物件型別  物件名 = 物件值;
            Student student = new Student();
            student.say();
        }
    
        //  static和類一起載入的
        public static void a(){
           // b();
        }
    
        //類例項化之後才存在
        //非靜態方法
        public  void b(){
    
        }
    
    }
    

    //學生類
    public class Student {
    
        //非靜態方法
        public void say(){
            System.out.println("學生說話了");
        }
    }
    
    • 形參和實參
    public class Demo03 {
        public static void main(String[] args) {
            //實際引數和形式引數的型別要對應!
            // new Demo03().add(1,2);
            int add = Demo03.add(1, 2);
            System.out.println(add);
        }
    
        public static int add(int a,int b){
            return a+b;
        }
    }
    
    • 值傳遞和引用傳遞
    //值傳遞
    public class Demo04 {
        public static void main(String[] args) {
           int a = 1;
            System.out.println(a);  //1
    
            Demo04.change(a);
    
            System.out.println(a);//1
        }
    
        //返回值為空
        public static void change(int a){
            a = 10;
        }
    }
    


    //之前引數傳入的是一個int屬性,然而這是傳的是person的類。改變類的屬性的值當然可以接收得到
    //引用傳遞:物件,本質還是值傳遞
    
    //理解 物件,記憶體!
    public class Demo05 {
        public static void main(String[] args) {
            Person person = new Person();
            System.out.println(person.name);    //null
    
            Demo05.change(person);
    
            System.out.println(person.name);    //lu
        }
    
        public static void change(Person person){
            //person是一個物件:指向是 --->Person person = new Person();這是一個具體的人,可以改變屬性。
            person.name = "lu";
        }
    }
    
    //定義了一個Person類,有一個屬性:name
    class Person{
        String name;
    }
    
    • this關鍵字:後面提