应用场景一:图形绘制系统
- 代码实现逻辑:
- 首先定义一个
Shape
类作为基类,包含通用的属性和方法。例如:
abstract class Shape {
// 颜色属性
protected String color;
// 设置颜色的方法
public void setColor(String color) {
this.color = color;
}
// 抽象的绘制方法,由子类具体实现
public abstract void draw();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("绘制一个颜色为 " + color + ",半径为 " + radius + " 的圆。");
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("绘制一个颜色为 " + color + ",宽为 " + width + ",高为 " + height + " 的矩形。");
}
}
- 在主程序中,利用多态特性,通过
Shape
类型的变量来引用不同子类的对象。
public class ShapeDrawingApp {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
circle.setColor("红色");
circle.draw();
Shape rectangle = new Rectangle(4.0, 6.0);
rectangle.setColor("蓝色");
rectangle.draw();
}
}
- 继承和多态协同工作原理:
Circle
和Rectangle
类通过继承Shape
类获得了color
属性和setColor
方法,实现了代码复用。而在主程序中,Shape
类型的变量可以引用不同子类的对象,根据实际引用对象的类型调用相应子类的draw
方法,这体现了多态性。
应用场景二:游戏角色系统
- 代码实现逻辑:
- 定义一个
Character
类作为基类,包含通用的属性和方法。
abstract class Character {
protected String name;
protected int health;
public Character(String name, int health) {
this.name = name;
this.health = health;
}
// 抽象的攻击方法,由子类具体实现
public abstract void attack();
}
class Warrior extends Character {
public Warrior(String name, int health) {
super(name, health);
}
@Override
public void attack() {
System.out.println(name + "(战士)发动近战攻击!");
}
}
class Mage extends Character {
public Mage(String name, int health) {
super(name, health);
}
@Override
public void attack() {
System.out.println(name + "(法师)释放魔法攻击!");
}
}
public class GameApp {
public static void main(String[] args) {
Character warrior = new Warrior("亚瑟", 100);
warrior.attack();
Character mage = new Mage("安琪拉", 80);
mage.attack();
}
}
- 继承和多态协同工作原理:
Warrior
和Mage
类继承Character
类获取了name
和health
属性以及构造函数,实现代码复用。在主程序中,Character
类型的变量可以分别引用Warrior
和Mage
类的对象,根据实际对象类型调用相应的attack
方法,展示了多态特性。