面向对象03:回顾方法的调用
方法的调用:递归
- 静态方法
- 非静态方法
- 形参和实参
- 值传递和引用传递
- this关键字
静态方法和动态方法
静态方法
-
关键字:static
-
特点:static 和类一起加载的,类a存在它就存在了
public static void a(){}
动态方法
- 需要实例化后才存在
public static void main(String[] args) {
//实例化这个类 new
//对象类型 对象名 = 对象值;
静态方法与动态方法01Student student = new 静态方法与动态方法01Student();
student.say();
}
形参和实参
形参
- 调用方法的时候分配内存,方法结束时解除内存
public int add(int a,int b){
return a+b;
}
实参
- 方法名(实参,实参)
形参和实参Demo03 add1 = new 形参和实参Demo03();
int a = add1.add(1,2);
public class 形参和实参Demo03 {
public static void main(String[] args) {
//动态方法先new
System.out.println("动态方法:");
形参和实参Demo03 add1 = new 形参和实参Demo03();
int a = add1.add(1,2);
System.out.println(a);
//有static静态方法直接调用
System.out.println("静态方法:");
int sub = 形参和实参Demo03.sub(2,1);
System.out.println(sub);
}
public int add(int a,int b){
return a+b;
}
public static int sub(int a,int b){
return a-b;
}
}
值传递(形参是值传递)
//值传递
public class 值传递Demo04 {
public static void main(String[] args) {
int a = 1;
System.out.println(a);
值传递Demo04.charge(a);//a = 10 只是把10赋值给了形参,由于没有返回值当方法结束值行参也消失了
System.out.println(a);
}
//放回值为空
public static void charge(int a){
a = 10;
}
}
引用传递
- 本质还是值传递,例子用传递了一个实例给方法
//引用传递 对象,本质还是值传递
//对象 内存
public class 引用传递Demo05 {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person);//null
引用传递Demo05.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;//null
}

浙公网安备 33010602011771号