面向对象(OOP)的核心:类是模板,对象是根据模板造出来的具体实例。

1. 定义类和创建对象

1
2
3
4
5
6
7
8
9
10
11
// 类:描述一类事物的属性和行为
public class Person {
// 字段(属性)
String name;
int age;

// 方法(行为)
public void sayHello() {
System.out.println("你好,我是" + name + ",今年" + age + "岁");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
// 用 new 创建对象
Person p = new Person();

// 给字段赋值
p.name = "小明";
p.age = 18;

// 调用方法
p.sayHello(); // 你好,我是小明,今年18岁
}
}

2. 构造方法

构造方法在 new 时自动调用,用来初始化对象。名字和类名相同,没有返回值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Person {
String name;
int age;

// 构造方法
public Person(String name, int age) {
this.name = name; // this.name 是字段,name 是参数
this.age = age;
}

// 无参构造方法
public Person() {
this("未知", 0); // 调用另一个构造方法
}

public void sayHello() {
System.out.println("你好,我是" + name + ",今年" + age + "岁");
}
}
1
2
3
4
5
6
7
8
9
public class Main {
public static void main(String[] args) {
Person p1 = new Person("小明", 18);
p1.sayHello(); // 你好,我是小明,今年18岁

Person p2 = new Person();
p2.sayHello(); // 你好,我是未知,今年0岁
}
}

要点:

  • 没写构造方法时,Java 会提供一个默认的无参构造
  • 一旦写了有参构造,默认无参构造就没了,需要自己补
  • this 指当前对象,用来区分字段和参数

3. static 静态成员

用 static 修饰的成员属于类本身,不属于某个对象,所有对象共享。

1
2
3
4
5
6
7
8
public class Counter {
static int count = 0; // 静态字段:所有对象共享
int id; // 实例字段:每个对象各自一份

public Counter() {
id = ++count; // 每次创建对象,count 加 1
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

System.out.println(c1.id); // 1
System.out.println(c2.id); // 2
System.out.println(c3.id); // 3

// 静态字段通过类名访问
System.out.println(Counter.count); // 3
}
}
1
2
3
4
5
6
public class MathUtil {
// 静态方法:不需要创建对象就能调用
public static int add(int a, int b) {
return a + b;
}
}
1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
int sum = MathUtil.add(3, 5); // 直接用类名调用
System.out.println(sum); // 8
}
}

4. 方法重载

同一个类里,方法名相同但参数列表不同,叫重载。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {
return a + b;
}

public int add(int a, int b, int c) {
return a + b + c;
}
}
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(1, 2)); // 3
System.out.println(c.add(1.5, 2.5)); // 4.0
System.out.println(c.add(1, 2, 3)); // 6
}
}

小结

  • 类 = 字段 + 方法,对象用 new 创建
  • 构造方法负责初始化,名字与类名相同
  • this 指当前对象
  • static 成员属于类,所有对象共享
  • 方法重载:同名方法,参数列表不同