回顾方法定义及加深
1.方法的调用:递归
- 静态方法
- 非静态方法
Student类:
package oop.demo01;
//学生类
public class Student {
//静态方法
public static void say(){
System.out.println("学生说话了");
}
//非静态方法
public void say01(){
System.out.println("学生说话了");
}
}
调用Student类中的静态和非静态方法
package oop.demo01;
public class Demo02 {
//静态方法 static
//非静态方法 没有加static
public static void main(String[] args) {
Student.say();//静态方法调用 类名.方法名
System.out.println("-----------------------");
//实例化这个类 new
//new Student().say01(); //非静态方法调用
//对象类型 对象名 = 对象值(实例化对象过程);
Student student = new Student();//new Student(); Alt+Enter
student.say01();//非静态方法调用
}
//和类一起加载的
public static void a(){
//b();//报错:非静态方法'b()'不能从静态上下文中引用
}
//类实例化之后才存在
public void b(){
}
}
输出:
- 形参和实参
package oop.demo01;
public class Demo03 {
public static void main(String[] args) {
//实际参数和形式参数的类型要对应!
int add = Demo03.add(1, 2);//Demo03.add(); Alt+Enter 这里的a,b是实际参数,是真实的值
System.out.println(add);//输出3
}
public static int add(int a,int b){ //这里的a,b是形式参数,只是个名字
return a+b;
}
}
- 值传递和引用传递(等学完面向对象后更容易理解)
值传递:
package oop.demo01;
//值传递
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){ //change改变
a = 10;
}
}
引用传递:
package oop.demo01;
//引用传递:一般传递对象,本质还是值传递
//对象,内存理解后这个就能看懂
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);//输出冰默
}
public static void change(Person person){
//person是一个对象,指向的是--> Person person = new Person();这是一个具体的人,可以改变属性!
person.name = "冰默";
}
}
//定义了一个Person类,有一个属性:name
class Person{
String name;//String默认值为null
}
- this关键字(后面学习)