面向对象(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) { Person p = new Person();
p.name = "小明"; p.age = 18;
p.sayHello(); } }
|
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.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();
Person p2 = new Person(); p2.sayHello(); } }
|
要点:
- 没写构造方法时,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; } }
|
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); System.out.println(c2.id); System.out.println(c3.id);
System.out.println(Counter.count); } }
|
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); } }
|
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)); System.out.println(c.add(1.5, 2.5)); System.out.println(c.add(1, 2, 3)); } }
|
小结
- 类 = 字段 + 方法,对象用
new 创建
- 构造方法负责初始化,名字与类名相同
this 指当前对象
static 成员属于类,所有对象共享
- 方法重载:同名方法,参数列表不同