面向对象03:回顾方法的调用
类名.方法名
方法的调用:例如递归:
- 静态方法
- 非静态方法
静态方法调用:
//静态方法调用
// Demo02类 中 调用 Student类 中 say()方法
// com.oop.Demo01 的Demo02类
package com.oop.Demo01;
public class Demo02 {
public static void main(String[] args) {
Student.say(); //类名.方法名。调用别的类
}
}
//com.oop.Demo01 的Student类
package com.oop.Demo01;
public class Student {
//静态方法
public static void say(){
System.out.println("学生说话了");
}
}
输出:
学生说话了
进程已结束,退出代码 0
非静态方法调用:
// 非静态方法调用
// Demo02类 中 调用 Student类 中 say()方法
package com.oop.Demo01;
public class Demo02 {
public static void main(String[] args) {
// Student.say(); //类名.方法名。调用别的类
Student student = new Student();
student.say();
}
}
// com.oop.Demo01 的Student类
package com.oop.Demo01;
public class Student {
//非静态方法
public void say(){
System.out.println("学生说话了");
}
}
静态方法调用和非静态方法调用的区别:
1.在静态调用中,被调用的类 在方法名中有 static ,调用类(demo02),直接调用
2.在非静态调用中,被调用的类 在方法名中没有 static,调用类(demo02)需要new 一个类名,再调用。
方法之间调用需要注意的一些东西:


把static去掉之后,两个方法可以互相调用。原因是有 static 存在的早,和类一起加载。没有static存在 相对有static晚。存在时间早的晚的,存在时间不一样的之间不能互相调用。 如互相调用需都有static,都没有static。


形参和实参:
package com.oop.Demo01;
public class Demo03 { //创建一个类叫demo03
public static void main(String[] args) {
//实际参数和形式参数的类型要对应!
// System.out.println(add(1,2));
int add = new Demo03().add(1,2);
System.out.println(add);
}
public static int add(int a,int b) {
return a+b;
}
}
输出:
3
进程已结束,退出代码 0
实际参数和形式参数的类型要对应!

值传递:
package com.oop.Demo01;
public class Demo04 {
public static void main(String[] args) {
//值传递
int a = 2;
System.out.println(a);
System.out.println("============");
Demo04.change(a); //把a的值带进change方法中
System.out.println(a);//1
}
//返回值为空
public static void change(int a) {
a = 10;
}
}
输出:
2
============
2
进程已结束,退出代码 0
引用传递:
package com.oop.Demo01;
public class Demo05 {
//引用传递 对象,本质还是值传递
//对象,内存
public static void main(String[] args) {
Person person = new Person(); //给Person方法个名字叫person
System.out.println(person.name); //null
Demo05.change(person);
System.out.println(person.name); //阿萨大
}
public static void change(Person person) { //change方法用的Person方法中的person
//person 是一个对象:指向的----->Person person = new Person();这是一个具体的人,可以改变属性!
person.name = "阿萨大";
}
static class Person {
String name; //null
}
}
输出:
null
阿萨大
进程已结束,退出代码 0

浙公网安备 33010602011771号