面向对象编程(Object-Oriented Programming, OOP)是一种编程范式,它使用“对象”来设计应用程序和软件。OOP的主要特性有三个:封装(Encapsulation)、继承(Inheritance)和多态(Polymorphism)。
1. 封装
封装是指将数据(属性)和操作数据的方法(函数)捆绑在一起,形成一个独立的实体,即对象。这样做可以隐藏对象的内部实现细节,只通过对象提供的接口与外界交互。
public class Person {
// 私有变量,外部无法直接访问
private String name;
private int age;
// 构造函数,用于初始化对象
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 公共方法,用于获取和设置私有变量的值
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 描述信息的方法
public void introduce() {
System.out.println("My name is " + name + " and I am " + age + " years old.");
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Person person = new Person("Alice", 25);
person.introduce(); // 输出:My name is Alice and I am 25 years old.
}
}
2. 继承
继承是面向对象编程中的一个重要概念,它允许一个类(子类)继承另一个类(父类)的属性和方法。子类可以重用父类的代码,并且可以增加新的属性和方法,或者重写父类的方法。
// 父类 Animal
public class Animal {
public void eat() {
System.out.println("The animal eats.");
}
}
// 子类 Dog 继承自 Animal
public class Dog extends Animal {
// 子类特有的方法
public void bark() {
System.out.println("The dog barks.");
}
// 重写父类的方法
@Override
public void eat() {
System.out.println("The dog eats dog food.");
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // 输出:The dog eats dog food.
dog.bark(); // 输出:The dog barks.
}
}
3. 多态
多态是指允许使用父类引用指向子类对象,并且在运行时根据实际的对象类型来决定调用哪个方法。Java 中实现多态的方式主要有方法重载(Overloading)和方法重写(Overriding)
// 父类 Shape
public class Shape {
public void draw() {
System.out.println("Drawing a shape...");
}
}
// 子类 Circle 继承自 Shape
public class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle...");
}
}
// 子类 Rectangle 继承自 Shape
public class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle...");
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
// 使用父类引用指向子类对象
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
// 调用 draw 方法,实际执行的是子类的方法
shape1.draw(); // 输出:Drawing a circle...
shape2.draw(); // 输出:Drawing a rectangle...
}
}