回顾方法及加深
-
方法的定义
1.修饰符
2.返回类型
package com.oop.demo01; //Demo1 类 public class Demo01 { //main 方法 public static void main(String[] args) { } /* * 修饰符 返回值类型 方法名(……){ * //方法体 * return 返回值; * } * */ public static String sayHello(){ return "Hello,wlod"; } //方法没有返回值 public void hello(){ return; } //比较大小 public int max(int a,int b){ return a>b?a:b;//三元运算符 } }
3.break和return的区别
break:跳出switch,结束循环
return:方法结束 ,返回值必须与方法定义的一样,返回一个结果或者返回空
4.方法名:注意规范 见名知意
5.参数列表:(参数类型,参数名)…
6.异常抛出:后面有
//数组下标越界 Arrayindexoutofbounds public void reandFile(String file) throws IOException{ }
-
方法的调用:递归
1.静态方法: +static
//非静态方法方法
public static void say(){
System.out.println("学生说话了");
}
public static void main(String[] args) {
//直接调用
Student.say();
}
2.非静态方法:没有+static
package com.oop.demo01;
public class Demo02 {
//非静态方法方法
public void say(){
System.out.println("学生说话了");
}
public static void main(String[] args) {
//实例化这个类
//对象类型 对象名字=对象值
Student student=new Student();
student.say();
}
//static和类一起加载的
public static void a(){
b();
}
//类实例化之后才存在
public void b(){
}
//静态方法 +static
//非静态方法 没有+static
}
3.形参和实参
package com.oop.demo01;
public class Demo03 {
public static void main(String[] args) {
//实际参数和形式参数的类型要对应
int add=new Demo03().add(1,2);
System.out.println(add);
}
public int add(int a,int b){
return a+b;
}
}
4.值传递和引用传递
值传递:
package com.oop.demo01;
//值传递
public class Demo04 {
public static void main(String[] args) {
int a=1;
System.out.println("1:"+a);//1
new Demo04().change(a);
System.out.println("2:"+a);//1
}
//返回值为空
public void change(int a){
a=10;
System.out.println("3:"+a);//10
}
}
引用传递:
package com.oop.demo01;
//引用传递:对象,本质还是值传递
//对象,内存
public class Demo05 {
public static void main(String[] args) {
Perosn perosn=new Perosn();
System.out.println(perosn.name);//null
new Demo05().change(perosn);
System.out.println(perosn.name);//我
}
public void change(Perosn perosn){
//perosn是一个对象:指向----》Perosn perosn=new Perosn();这是一个具体的人,可以改变属性
perosn.name="我";
}
}
//定义一个perosn类,有一个属性:name
class Perosn{
String name;//打印出来null
}
5.this关键字