Java基础 - Java Object Oriented Programming

封装

封装就是“把数据和操作数据的方法打包在一起”,同时隐藏内部的实现细节。比如将字段用private修饰,只暴露getter和setter。

  • 防止外部随意修改对象的内部状态。
  • 保持代码的安全性和清晰性。

继承

子类可以继承父类的属性和方法(使用 Extends 来继承)。

public class Animal {
    void makeSound() {
        System.out.println("Some sound...");
    }
}

// Dog 类继承了 Animal 类,也可以调用 makeSound()
public class Dog extends Animal {
    void bark() {
        System.out.println("Woof!");
    }
}

多态

编译时多态

也叫方法重载(Overloading),是指在编译期间就已经确定了哪个方法会被调用。

public class Calculator {
    // 重载 add 方法
    int add(int a, int b) {
        return a + b;
    }

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

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

编译器根据你传入的参数类型和个数,在编译阶段 就能决定调用哪个方法。

运行时多态

也叫 方法重写(Overriding),是指在运行期间才能决定调用哪个方法。

class Animal {
    void makeSound() {
        System.out.println("Some animal sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Meow!");
    }
}

Animal a = new Dog();
a.makeSound();  // Woof!

a = new Cat();
a.makeSound();  // Meow!

虽然变量类型是 Animal,但真正调用的是对象 Dog 或 Cat 中的 makeSound() 方法。

接口和抽象类

抽象类

抽象类是一种不能直接创建对象的类,它是为了被继承而存在的。子类是否必须实现父抽象类的抽象方法。

abstract class Animal {
    String name;  // 添加 name 属性

    abstract void makeSound(); // 留给子类实现

    void eat() {
        System.out.println(name + " is eating.");
    }
}

class Dog extends Animal {
    // 实现抽象方法
    void makeSound() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.name = "Buddy";
        a.eat();        // 输出: Buddy is eating.
        a.makeSound();  // 输出: Woof!
    }
}

接口

接口(interface)是一些方法的集合,它定义了类应该遵守的一组规范或能力。

interface Flyable {
    void fly();  // 自动是 public abstract
}

class Bird implements Flyable {
    public void fly() {
        System.out.println("Bird is flying");
    }
}

class Airplane implements Flyable {
    public void fly() {
        System.out.println("Airplane is flying");
    }
}

Flyable f1 = new Bird();
Flyable f2 = new Airplane();
f1.fly();  // Bird is flying
f2.fly();  // Airplane is flying

一个类可以实现多个接口:

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck implements Flyable, Swimmable {
    public void fly() { System.out.println("Duck flies"); }
    public void swim() { System.out.println("Duck swims"); }
}

此外

  1. 接口中可以定义 default 方法,提供默认实现。
  2. 接口中可以定义 static 方法,不属于实现类,直接通过接口调用。
  3. 接口中可以定义 private 方法,用于接口内部复用代码。

Java关键字

  1. 访问控制
  • public:公有,所有地方都可以访问
  • private: 私有,只能在本类中访问
  • protected: 受保护,同包 + 子类可访问
  1. final:表示不可修改:类不能继承、方法不能重写、变量不能变值

Java基础 - Java Object Oriented Programming
http://example.com/2025/07/06/JAVA_basis/java-oop/
Author
Songlin Zhao
Posted on
July 6, 2025
Licensed under