面向对象编程(Object-Oriented Programming,简称 OOP)是一种编程范式,它使用“对象”来设计软件。
面向对象编程的本质是:以类的方式组织代码,以对象的组织(封装)数据。
三大特性:
- 封装
- 继承
- 多态
从认识角度考虑是先有对象后有类。对象,是具体的事务。类,是抽象的,是对对象的抽象
从代码运行角度考虑是先有类后有对象。类是对象的模板。
在Java中,面向对象的概念是核心特性之一,它强调以下几个关键概念:
类(Class)
类是创建对象的蓝图或模板。它定义了对象的数据属性和可以执行的方法。
public class Car {
String brand;
int wheels;
public Car(String brand) {
this.brand = brand;
this.wheels = 4;
}
public void drive() {
System.out.println("Car is driving");
}
}
对象(Object)
对象是类的实例。使用new
关键字可以创建对象。
Car myCar = new Car("Toyota");
封装(Encapsulation)
封装是将对象的数据(属性)和代码(方法)绑定在一起的过程,并对外隐藏实现的细节。在Java中,通常通过访问修饰符(如private, public)来实现封装。
private String brand; // 私有属性,外部无法直接访问
public String getBrand() { // 公开的getter方法
return brand;
}
public void setBrand(String brand) { // 公开的setter方法
this.brand = brand;
}
继承(Inheritance)
继承允许一个类继承另一个类的属性和方法,这有助于代码的重用和减少冗余。
public class ElectricCar extends Car { // ElectricCar继承自Car
private int batteryLevel;
public ElectricCar(String brand) {
super(brand); // 调用父类的构造方法
this.batteryLevel = 100;
}
public void chargeBattery() {
System.out.println("Battery is charging");
}
}
多态(Polymorphism)
多态允许以统一的方式处理不同类型的对象。在Java中,多态可以通过接口(Interface)和抽象类(Abstract Class)来实现。
public interface Drivable {
void drive();
}
public class Car implements Drivable {
public void drive() {
System.out.println("Car is driving");
}
}
public class Bicycle implements Drivable {
public void drive() {
System.out.println("Bicycle is being ridden");
}
}
public class VehicleManager {
public void maintain(Drivable vehicle) {
vehicle.drive();
}
}
抽象类(Abstract Class)
抽象类是不能被实例化的类,它通常用作其他类的基类。抽象类可以包含抽象方法(没有实现的方法)和具体方法。
public abstract class Animal {
public abstract void makeSound(); // 抽象方法
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
public void makeSound() {
System.out.println("Woof woof");
}
}
接口(Interface)
接口定义了一组方法,但不包含实现。类可以实现一个或多个接口,从而承诺提供接口中定义的所有方法的实现。
public interface Flyable {
void fly();
}
public class Bird implements Flyable {
public void fly() {
System.out.println("Bird is flying");
}
}
面向对象编程使得软件设计更加模块化、灵活和可扩展。通过使用类和对象,开发者可以创建复杂的系统,同时保持代码的清晰和易于维护。