Java面向对象编程核心概念详解
一、类与对象
1.1 类的定义
类是对现实生活中具有相同属性和行为的事物的抽象描述,是一种模板或蓝图。对象是类的实例化结果,具有具体的数据和功能。
定义语法:
public class Person {
// 实例变量
private String name;
private int age;
// 静态方法
public static void work() {
System.out.println("工作中");
}
}
对象创建:
Person p = new Person();
p.name = "张三";
p.age = 25;
1.2 构造函数
构造函数用于初始化对象,与类名相同且无返回值。当创建对象时,构造函数会自动执行。
无参构造函数:
public class Animal {
public String type;
public int count;
public boolean isWild;
public Animal() {
// 默认初始化:数值型为0,引用型为null,布尔型为false
}
public static void main(String[] args) {
Animal a = new Animal();
System.out.println(a.type); // null
System.out.println(a.count); // 0
System.out.println(a.isWild); // false
}
}
带参构造函数:
public class Animal {
public String type;
public int count;
public boolean isWild;
public Animal(String t, int c, boolean w) {
this.type = t;
this.count = c;
this.isWild = w;
}
public static void main(String[] args) {
Animal dog = new Animal("狗", 3, false);
System.out.println(dog.type); // 狗
System.out.println(dog.count); // 3
System.out.println(dog.isWild); // false
}
}
构造函数重载:
public class Student {
private String name;
private int score;
private String gender;
// 无参构造
public Student() {}
// 单参数构造
public Student(String n) {
this.name = n;
}
// 双参数构造
public Student(String n, int s) {
this.name = n;
this.score = s;
}
// 三参数构造
public Student(String n, int s, String g) {
this.name = n;
this.score = s;
this.gender = g;
}
}
1.3 this与super关键字
this关键字:指向当前对象本身,用于区分成员变量与局部变量的重名问题。
public class Company {
public String name = "集团";
public void show(String name) {
System.out.println(name); // 参数值
System.out.println(this.name); // 成员变量值
}
public static void main(String[] args) {
Company c = new Company();
c.show("分公司");
}
}
super关键字:指向父类对象,用于调用父类的方法和属性。
// 父类
public class Vehicle {
protected String brand = "比亚迪";
public void run() {
System.out.println("车辆行驶中");
}
public Vehicle() {
System.out.println("父类构造函数执行");
}
}
// 子类
public class Car extends Vehicle {
private String model = "秦";
public Car() {
super(); // 调用父类构造器,必须在第一行
System.out.println("子类构造函数执行");
}
@Override
public void run() {
super.run(); // 调用父类方法
System.out.println("汽车行驶中");
}
public void test() {
System.out.println(this.model); // 秦
System.out.println(super.brand); // 比亚迪
}
}
关键区别:
- this()调用同类其他构造器,super()调用父类构造器
- 两者都必须在构造器第一行,不能同时使用
- this表示当前对象,super表示父类对象
- 静态方法中不能使用this和super
1.4 成员变量与局部变量
| 特征 | 成员变量 | 局部变量 |
|---|---|---|
| 声明位置 | 类中,方法外 | 方法内或代码块中 |
| 存储位置 | 堆内存 | 栈内存 |
| 生命周期 | 随对象创建/销毁 | 随方法调用结束 |
| 初始化 | 系统自动赋值 | 必须手动赋值 |
| 修饰符 | 可用多种修饰符 | 只能用final |
1.5 new关键字与引用
Book b = new Book("Java编程");
// 1. 在堆区分配内存
// 2. 初始化成员变量
// 3. 调用构造器
// 4. 返回内存地址给引用变量b
对象与引用的区别:
- 对象:保存在堆中,存储实际数据
- 引用:保存在栈中,存储对象地址
- 一个对象可有多个引用,一个引用只能指向一个对象
1.6 对象相等与引用相等
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false,引用不同
System.out.println(s1.equals(s2)); // true,内容相同
二、面向对象三大特性
2.1 封装
封装是将数据和操作封装在类内部,对外提供访问接口,隐藏实现细节。
public class Account {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
2.2 继承
继承使子类可以复用父类的属性和方法,Java只支持单继承。
// 父类
public class Shape {
public String color = "红色";
public double area() {
return 0;
}
}
// 子类
public class Circle extends Shape {
private double radius = 5;
@Override
public double area() {
return Math.PI * radius * radius;
}
}
方法重写规则:
- 方法名相同,参数列表相同
- 访问修饰符不能缩小范围
- 不能重写static和final方法
- 异常范围只能缩小不能扩大
2.3 多态
多态指同一引用调用同一方法产生不同行为。
public class Animal {
public void speak() {
System.out.println("动物叫声");
}
}
public class Dog extends Animal {
@Override
public void speak() {
System.out.println("汪汪汪");
}
}
public class Cat extends Animal {
@Override
public void speak() {
System.out.println("喵喵喵");
}
}
// 测试
public class Test {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.speak(); // 汪汪汪
a2.speak(); // 喵喵喵
}
}
instanceof关键字:
Animal a = new Dog();
if (a instanceof Dog) {
System.out.println("是Dog类型");
}
if (a instanceof Animal) {
System.out.println("是Animal类型");
}
2.4 抽象类
抽象类不能实例化,包含抽象方法的类必须声明为抽象类。
public abstract class Employee {
private String name;
public Employee(String n) {
this.name = n;
}
public abstract double calculateSalary();
public String getName() {
return name;
}
}
public class Manager extends Employee {
private double baseSalary;
public Manager(String n, double s) {
super(n);
this.baseSalary = s;
}
@Override
public double calculateSalary() {
return baseSalary * 1.5;
}
}
2.5 接口
接口定义规范,实现类必须重写所有抽象方法。接口支持多实现。
public interface Drawable {
void draw();
default void show() {
System.out.println("显示图形");
}
}
public interface Movable {
void move();
}
public class Ball implements Drawable, Movable {
@Override
public void draw() {
System.out.println("画球");
}
@Override
public void move() {
System.out.println("球在移动");
}
}
2.6 内部类
成员内部类:
public class Outer {
private int value = 100;
public class Inner {
public void show() {
System.out.println("外部类值: " + value);
}
}
public static void main(String[] args) {
Outer o = new Outer();
Outer.Inner i = o.new Inner();
i.show();
}
}
静态内部类:
public class Outer {
public static class StaticInner {
public void test() {
System.out.println("静态内部类");
}
}
}
局部内部类:
public class Outer {
public void method() {
class LocalInner {
public void display() {
System.out.println("局部内部类");
}
}
LocalInner li = new LocalInner();
li.display();
}
}
三、异常处理
3.1 异常分类
- Error:JVM错误,无法处理
- Exception:可处理异常
- 运行时异常:RuntimeException及其子类
- 编译时异常:除RuntimeException外的异常
3.2 异常处理机制
public class ExceptionTest {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("算术异常: " + e.getMessage());
} catch (Exception e) {
System.out.println("其他异常");
} finally {
System.out.println("总是执行");
}
}
}
3.3 throw与throws
public class ThrowDemo {
public void check(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
}
public static void main(String[] args) {
ThrowDemo td = new ThrowDemo();
try {
td.check(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
3.4 自定义异常
public class ScoreException extends Exception {
public ScoreException(String message) {
super(message);
}
}
public class Student {
public void setScore(int score) throws ScoreException {
if (score < 0 || score > 100) {
throw new ScoreException("分数必须在0-100之间");
}
}
}