OOP详解
以类的方式组织代码,以对象的方式组织(封装)数据
什么是面向对象
封装 【口袋装数据,留个口,可以用】
继承 【儿子和父亲】
多态 【同一个事物表现出多种形态】
对象和类
实际:先有对象后有类
代码:先有类后有对象【设计代码!!!】
方法加深与回顾
方法的定义:修饰符、返回类型等
// main方法
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(Max(a, b));
}
// 其他方法
public static int Max(int a, int b) {
return a > b ? a : b;
}
tip:break、continue、return
continue:结束一次循环
break:结束整个循环
return:结束整个方法
异常
throws,后面会自动补充的
// 异常
public static void readFile(String fileName) throws IOException{
}
方法的调用
静态方法,可以直接调用(有static的);非静态方法,必须new了这个类的对象,才能调用。
// 调用同一个包中的类的方法
Student.Say(); // say为静态方法
Student student = new Student(); // Cry为非静态方法
student.Cry();
static是和类一起加载的,时间片很早; 非static方法是类实例化之后才存在。所以,static方法不能调用同类中的非static方法。

传参
a. 形参和实参
// main方法
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(Max(a, b));
Demo1.Max(3,4); // 通过类名调用
}
// 其他方法
public static int Max(int a, int b) {
return a > b ? a : b;
}
b. 值传递和引用传递
值传递
没有改变实参的值
public static void main(String[] args) {
int number = 1;
System.out.println("number = " + number);
changeValue(number);
System.out.println("after, number = " + number); // 还是1
}
public static void changeValue(int a){
a = 10;
}
引用传递
一个class文件中,只能有一个public class,为该类;可以有多个class,用于内部使用
类对象作为参数,是引用传递
public class Demo4 {
// 引用传递
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.Name); // 默认Name = null
Change(person); // 引用传递
System.out.println(person.Name);; // 这里改了
}
public static void Change(Person person){
person.Name = "大文";
}
}
// 定一个person类,注意这儿是class,不是public class,class可以有多个,public class只能有一个
class Person{
String Name;
}