Day7-2 回顾方法的定义及调用
方法的定义
-
修饰符
-
返回类型
-
-
break:跳出switch语句、结束循环
-
return:结束方法,返回一个结果
-
-
方法名:首字母小写驼峰命名法。见名知意
-
参数列表:参数类型,参数名
-
异常抛出
package com.oop.demo01; import java.io.IOException; //Demo01 就是一个类 public class Demo01 { //main 方法 public static void main(String[] args) { } /* 修饰符 返回值类型 方法名(参数列表){ 方法体 return 返回值; } */ public String sayHello() { return "Hello World!"; } public int max(int a, int b) { return a > b ? a : b;//三元运算符 } public void print(){ return; } public void readFile(String file)throws IOException{ } }
方法的调用
-
静态方法
-
非静态方法
package com.oop.demo01; public class Demo02 { public static void main(String[] args) { //实例化非静态方法 new //对象类型 对象名=对象值 Student student = new Student(); student.say(); } //静态方法和类一起加载 //非静态方法实例化之后加载 }
-
形参和实参
package com.oop.demo01; public class Demo03 { public static void main(String[] args) { //实参和形参的类型要对应 Demo03 demo03 = new Demo03(); int add = demo03.add(1, 2); //int add = new Demo03().add(1,2); System.out.println(add); } public int add(int a,int b){ return a+b; } }
-
值传递和引用传递
package com.oop.demo01; //引用传递 传递对象,本质还是值传递 public class Demo05 { public static void main(String[] args) { Person person = new Person(); System.out.println(person.name);//null change(person); System.out.println(person.name); } public static void change(Person person){ //person是一个对象,指向的Person person=new Person();这是一个具体的实例,可以改变属性 person.name="秦疆"; } } //定义了一个person类,有一个name属性 class Person{ String name;//String类型默认值null }

浙公网安备 33010602011771号