## 多态
多态是面向对象编程中的一个重要概念,它允许同一个接口接受不同的数据类型。在Java中,多态主要通过继承和接口实现。
### 案例:动物的叫声
假设我们有一个`Animal`类,它有一个`makeSound()`方法。不同的动物有不同的叫声,我们可以通过多态来实现这一点。```java
// 动物基类
class Animal {
void makeSound() {
System.out.println("动物发出声音");
}
}
// 狗类继承自Animal类
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("汪汪");
}
}
// 猫类继承自Animal类
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("喵喵");
}
}
// 测试多态
public class PolymorphismExample {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // 输出:汪汪
myCat.makeSound(); // 输出:喵喵
}
}
```
## 继承
继承允许一个类(子类)继承另一个类(父类)的属性和方法。这有助于代码复用和建立一个层次结构。
### 案例:车辆的层次结构
我们可以创建一个`Vehicle`类,然后创建`Car`和`Bike`类继承自`Vehicle`类。```java
// 车辆基类
class Vehicle {
void start() {
System.out.println("车辆启动");
}
}
// 汽车类继承自Vehicle类
class Car extends Vehicle {
void start() {
System.out.println("汽车启动");
}
}
// 自行车类继承自Vehicle类
class Bike extends Vehicle {
void start() {
System.out.println("自行车启动");
}
}
// 测试继承
public class InheritanceExample {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBike = new Bike();
myCar.start(); // 输出:汽车启动
myBike.start(); // 输出:自行车启动
}
}
```
## 封装
封装是将对象的实现细节隐藏起来,只暴露出一个可以被外界访问和操作的接口。
### 案例:银行账户
我们可以创建一个`BankAccount`类,封装账户余额和存款、取款操作。```java
// 银行账户类
class BankAccount {
private double balance; // 私有属性,隐藏实现细节
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("存入:" + amount);
}
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("余额不足");
} else {
balance -= amount;
System.out.println("取出:" + amount);
}
}
public double getBalance() {
return balance;
}
}
// 测试封装
public class EncapsulationExample {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
System.out.println("当前余额:" + account.getBalance());
}
}
```
## 结论
通过上述案例,我们可以看到多态、继承和封装如何帮助我们编写更加模块化、可维护和易于扩展的代码。这些特性是Java面向对象编程的核心,理解它们对于成为一名优秀的Java开发者至关重要。
##Demo1:形状的多态
### 描述
在几何学中,我们有多种形状,如圆形、矩形等。每种形状都有计算面积的方法。我们可以使用多态来统一处理不同形状的面积计算。
### 源码```java
// 形状接口
interface Shape {
double getArea();
}
// 圆形类实现Shape接口
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 矩形类实现Shape接口
class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
// 测试多态
public class ShapePolymorphism {
public static void main(String[] args) {
Shape myCircle = new Circle(5);
Shape myRectangle = new Rectangle(4, 5);
System.out.println("圆形面积:" + myCircle.getArea());
System.out.println("矩形面积:" + myRectangle.getArea());
}
}
```
## Demo2:继承与抽象类的使用
### 描述
抽象类不能被实例化,但可以被继承。我们定义一个抽象的`Animal`类,然后创建具体的`Dog`和`Cat`类继承它。
### 源码```java
// 抽象动物类
abstract class Animal {
abstract void makeSound();
void eat() {
System.out.println("动物在吃东西");
}
}
// 狗类继承自Animal类
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("狗叫:汪汪");
}
}
// 猫类继承自Animal类
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("猫叫:喵喵");
}
}
// 测试继承
public class InheritanceWithAbstraction {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // 输出:狗叫:汪汪
myCat.makeSound(); // 输出:猫叫:喵喵
myDog.eat(); // 输出:动物在吃东西
myCat.eat(); // 输出:动物在吃东西
}
}
```
## Demo3:封装在银行交易中的应用
### 描述
银行交易是一个敏感的操作,需要确保安全性和数据的完整性。通过封装,我们可以隐藏实现细节,只提供必要的接口给用户。
### 源码
```java
// 银行交易类
class BankTransaction {
private double amount;
private String type; // 可以是"deposit"或"withdrawal"
private boolean isCompleted;
public BankTransaction(double amount, String type) {
this.amount = amount;
this.type = type;
this.isCompleted = false;
}
public void execute() {
if (type.equals("deposit")) {
// 存款逻辑
System.out.println("存款:" + amount);
isCompleted = true;
} else if (type.equals("withdrawal")) {
// 取款逻辑
System.out.println("取款:" + amount);
isCompleted = true;
}
}
public boolean isTransactionCompleted() {
return isCompleted;
}
}
// 测试封装
public class BankTransactionExample {
public static void main(String[] args) {
BankTransaction deposit = new BankTransaction(1000, "deposit");
BankTransaction withdrawal = new BankTransaction(500, "withdrawal");
deposit.execute(); // 输出:存款:1000
withdrawal.execute(); // 输出:取款:500
System.out.println("存款交易完成:" + deposit.isTransactionCompleted());
System.out.println("取款交易完成:" + withdrawal.isTransactionCompleted());
}
}
```
以上三个案例进一步展示了Java中的多态、继承和封装如何应用于实际编程中,帮助我们构建更加灵活、安全和可维护的代码。
## Demo4:多态在图形界面中的应用
### 描述
在图形用户界面(GUI)编程中,多态允许我们为不同类型的组件定义统一的接口。
### 源码```java
// 组件接口
interface Component {
void paint();
}
// 按钮类
class Button implements Component {
@Override
public void paint() {
System.out.println("绘制按钮");
}
}
// 文本框类
class TextBox implements Component {
@Override
public void paint() {
System.out.println("绘制文本框");
}
}
// 测试多态
public class GUIComponents {
public static void main(String[] args) {
Component[] components = {new Button(), new TextBox()};
for (Component component : components) {
component.paint();
}
}
}
```
## Demo5:继承在员工管理系统中的应用
### 描述
在一个员工管理系统中,我们有不同类型的员工,如全职员工、兼职员工和合同工。继承可以帮助我们共享和扩展员工的基本属性和行为。
### 源码```java
// 员工基类
class Employee {
protected String name;
protected int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
public void work() {
System.out.println(name + "在工作");
}
}
// 全职员工类
class FullTimeEmployee extends Employee {
private double salary;
public FullTimeEmployee(String name, int id, double salary) {
super(name, id);
this.salary = salary;
}
public void receiveSalary() {
System.out.println(name + "收到工资:" + salary);
}
}
// 测试继承
public class EmployeeSystem {
public static void main(String[] args) {
FullTimeEmployee fte = new FullTimeEmployee("张三", 1, 5000);
fte.work(); // 输出:张三在工作
fte.receiveSalary(); // 输出:张三收到工资:5000
}
}
```
## Demo6:封装在个人信息管理中的应用
### 描述
封装可以帮助我们保护个人信息不被外部直接访问和修改,通过方法提供访问和修改的接口。
### 源码```java
// 个人信息类
class PersonInfo {
private String firstName;
private String lastName;
private int age;
public PersonInfo(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// 获取全名
public String getFullName() {
return firstName + " " + lastName;
}
// 设置年龄
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
// 获取年龄
public int getAge() {
return age;
}
}
// 测试封装
public class PersonInfoExample {
public static void main(String[] args) {
PersonInfo person = new PersonInfo("李", "四", 30);
System.out.println("姓名:" + person.getFullName()); // 输出:姓名:李 四
person.setAge(31);
System.out.println("年龄:" + person.getAge()); // 输出:年龄:31
}
}
```
这三个案例进一步展示了多态、继承和封装在不同场景下的应用,帮助我们理解这些概念在实际编程中的实用性和重要性。