在 Java 核心中,多态性 是一个易于理解的概念。多态的定义是:Poly
表示 许多,morphos
表示 形式。它描述了语言的一种特性,即允许根据上下文在不同情况下正确解释同一个单词或符号。Java 中有两种多态性。例如,在英语中,动词 run
与 a footrace
、business
或 a computer
一起使用时会有不同的含义。您可以根据与 run
搭配使用的其他单词来理解 run
的含义。
案例 |
|
---|---|
01 | 编写一个 Java 程序,创建一个带有 Sound() 方法的基类 Animal (动物家族)。创建两个子类 Bird 和 Cat 。在每个子类中重载 Sound() 方法,为每种动物发出特定的声音。 |
02 | 编写一个 Java 程序,创建一个带有名为 speedUp() 方法的类 Vehicle 。创建两个子类 Car 和 Bicycle 。在每个子类中重载 speedUp() 方法,以不同的方式提高车辆的速度。 |
03 | 编写一个 Java 程序,创建一个带有名为 calculateArea() 方法的基类 Shape。创建三个子类: 圆形、矩形和三角形。在每个子类中重载 calculateArea() 方法,以计算并返回形状的面积。 |
04 | 编写一个 Java 程序,创建一个 Employee 类,其中包含一个名为 calculateSalary() 的方法。创建两个子类 Manager 和 Programmer 。在每个子类中,覆盖 calculateSalary() 方法,以根据其特定角色计算并返回工资。 |
05 | 编写一个 Java 程序,创建一个基类 Sports,其中包含一个名为 play() 的方法。创建三个子类: 足球、篮球和橄榄球。在每个子类中重载 play() 方法,为每项运动播放特定的语句。 |
06 | 编写一个 Java 程序,创建一个具有 getArea() 和 getPerimeter() 方法的 Shape 类。创建三个子类: 圆形、矩形和三角形。在每个子类中重载 getArea() 和 getPerimeter() 方法,以计算并返回各自形状的面积和周长。 |
07 | 编写一个 Java 程序,创建一个带有 move() 和 makeSound() 方法的基类 Animal。创建两个子类 Bird 和 Panthera。在每个子类中覆盖 move() 方法,以描述每种动物如何移动。同时,覆盖每个子类中的 makeSound() 方法,为每种动物发出特定的声音。 |
08 | 编写一个 Java 程序,创建一个带有 draw() 和 calculateArea() 方法的基类 Shape。创建三个子类: 圆形、正方形和三角形。覆盖每个子类中的 draw() 方法以绘制相应的形状,覆盖 calculateArea() 方法以计算并返回每个形状的面积。 |
09 | 编写一个 Java 程序,创建一个带有 deposit() 和 withdraw() 方法的基类 BankAccount。创建两个子类 SavingsAccount 和 CheckingAccount。重写每个子类中的 withdraw() 方法,以规定不同的取款限额和费用。 |
10 | 编写一个 Java 程序,创建一个带有 eat() 和 sound() 方法的基类 Animal。创建三个子类: 狮子、老虎和豹。在每个子类中覆盖 eat() 方法,以描述每种动物吃什么。此外,覆盖 sound() 方法,为每种动物发出特定的声音。 |
11 | 编写一个 Java 程序,创建一个基类 Vehicle,其中包含 startEngine() 和 stopEngine() 方法。创建两个子类汽车和摩托车。在每个子类中重载 startEngine() 和 stopEngine() 方法,以不同的方式启动和停止发动机。 |
12 | 编写一个 Java 程序,创建一个带有 draw() 和 calculateArea() 方法的基类 Shape。创建两个子类 Circle 和 Cylinder。在每个子类中覆盖 draw() 方法,以绘制相应的形状。此外,在 Cylinder 子类中重载 calculateArea() 方法,以计算并返回圆柱体的总表面积。 |
案例 01
编写一个 Java 程序,创建一个带有 Sound()
方法的基类 Animal
(动物家族)。创建两个子类 Bird
和 Cat
。在每个子类中重载 Sound()
方法,为每种动物发出特定的声音。
// Animal.java
// Base class Animal
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// Bird.java
// Subclass Bird
public class Bird extends Animal {
@Override
public void makeSound() {
System.out.println("The bird chirps");
}
}
// Cat.java
// Subclass Cat
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Bird bird = new Bird();
Cat cat = new Cat();
animal.makeSound(); // Output: The animal makes a sound
bird.makeSound(); // Output: The bird chirps
cat.makeSound(); // Output: The cat meows
}
}
The animal makes a sound
The bird chirps
The cat meows
案例 02
编写一个 Java 程序,创建一个带有名为 speedUp()
方法的类 Vehicle
。创建两个子类 Car
和 Bicycle
。在每个子类中重载 speedUp()
方法,以不同的方式提高车辆的速度。
// Vehicle.java
// Base class Vehicle
class Vehicle {
private int speed;
public void speedUp() {
speed += 10;
}
public int getSpeed() {
return speed;
}
}
// Car.java
// Subclass Car
class Car extends Vehicle {
@Override
public void speedUp() {
super.speedUp();
System.out.println("\nCar speed increased by 22 units.");
}
}
// Motorcycle.java
// Subclass Motorcycle
class Motorcycle extends Vehicle {
@Override
public void speedUp() {
super.speedUp();
System.out.println("Motorcycle speed increased by 12 units");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car();
Motorcycle motorcycle = new Motorcycle();
System.out.println("Car initial speed: " + car.getSpeed());
System.out.println("Motorcycle initial speed: " + motorcycle.getSpeed());
car.speedUp();
motorcycle.speedUp();
System.out.println("\nCar speed after speeding up: " + car.getSpeed());
System.out.println("Motorcycle speed after speeding up: " + motorcycle.getSpeed());
}
}
Car initial speed: 0
Motorcycle initial speed: 0
Car speed increased by 22 units.
Motorcycle speed increased by 12 units
Car speed after speeding up: 10
Motorcycle speed after speeding up: 10
案例 03
编写一个 Java 程序,创建一个带有名为 calculateArea()
方法的基类 Shape。创建三个子类: 圆形、矩形和三角形。在每个子类中重载 calculateArea()
方法,以计算并返回形状的面积。
// Shape.java
// Base class Shape
public class Shape {
public double calculateArea() {
return 0; // Default implementation returns 0
}
}
// Circle.java
// Subclass Circle
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius; // Calculate area of circle
}
}
// Rectangle.java
// Subclass Rectangle
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height; // Calculate area of rectangle
}
}
// Triangle.java
// Subclass Triangle
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double calculateArea() {
return 0.5 * base * height; // Calculate area of triangle
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(4);
System.out.println("Area of Circle: " + circle.calculateArea());
Rectangle rectangle = new Rectangle(12, 34);
System.out.println("\nArea of Rectangle: " + rectangle.calculateArea());
Triangle triangle = new Triangle(5, 9);
System.out.println("\nArea of Triangle: " + triangle.calculateArea());
}
}
Area of Circle: 50.26548245743669
Area of Rectangle: 408.0
Area of Triangle: 22.5
案例 04
编写一个 Java 程序,创建一个 Employee
类,其中包含一个名为 calculateSalary()
的方法。创建两个子类 Manager
和 Programmer
。在每个子类中,覆盖 calculateSalary()
方法,以根据其特定角色计算并返回工资。
// Employee.java
// Base class Employee
class Employee {
private String name;
private String role;
public Employee(String name, String role) {
this.name = name;
this.role = role;
}
public String getName() {
return name;
}
public String getRole() {
return role;
}
public double calculateSalary() {
return 0.0;
}
}
// Manager.java
// Subclass Manager
class Manager extends Employee {
private double baseSalary;
private double bonus;
public Manager(String name, double baseSalary, double bonus) {
super(name, "Manager");
this.baseSalary = baseSalary;
this.bonus = bonus;
}
@Override
public double calculateSalary() {
return baseSalary + bonus;
}
}
// Programmer.java
// Subclass Programmer
class Programmer extends Employee {
private double baseSalary;
private double overtimePay;
public Programmer(String name, double baseSalary, double overtimePay) {
super(name, "Programmer");
this.baseSalary = baseSalary;
this.overtimePay = overtimePay;
}
@Override
public double calculateSalary() {
return baseSalary + overtimePay;
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Employee emp1 = new Manager("Lilo Heidi", 7500.0, 1500.0);
Employee emp2 = new Programmer("Margrit Cathrin", 5000.0, 600.0);
System.out.println("Manager: " + emp1.getName() + "\nRole: " + emp1.getRole() + "\nSalary: $" + emp1.calculateSalary());
System.out.println("\nProgrammer: " + emp2.getName() + "\nRole: " + emp2.getRole() + "\nSalary: $" + emp2.calculateSalary());
}
}
Manager: Lilo Heidi
Role: Manager
Salary: $9000.0
Programmer: Margrit Cathrin
Role: Programmer
Salary: $5600.0
案例 05
编写一个 Java 程序,创建一个基类 Sports,其中包含一个名为 play()
的方法。创建三个子类: 足球、篮球和橄榄球。在每个子类中重载 play()
方法,为每项运动播放特定的语句。
// Sports.java
// Base class Sports
class Sports {
public void play() {
System.out.println("Playing a sport...\n");
}
}
// Football.java
// Subclass Football
class Football extends Sports {
@Override
public void play() {
System.out.println("Playing football...");
}
}
// Basketball.java
// Subclass Basketball
class Basketball extends Sports {
@Override
public void play() {
System.out.println("Playing basketball...");
}
}
// Rugby.java
// Subclass Rugby
class Rugby extends Sports {
@Override
public void play() {
System.out.println("Playing rugby...");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Sports sports = new Sports();
Football football = new Football();
Basketball basketball = new Basketball();
Rugby rugby = new Rugby();
sports.play();
football.play();
basketball.play();
rugby.play();
}
}
Playing a sport...
Playing football...
Playing basketball...
Playing rugby...
案例 06
编写一个 Java 程序,创建一个具有 getArea()
和 getPerimeter()
方法的 Shape 类。创建三个子类: 圆形、矩形和三角形。在每个子类中重载 getArea()
和 getPerimeter()
方法,以计算并返回各自形状的面积和周长。
// Shape.java
// Base class Shape
abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
// Circle.java
// Subclass Circle
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// Rectangle.java
// Subclass Rectangle
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
// Triangle.java
// Subclass Triangle
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double getPerimeter() {
return side1 + side2 + side3;
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
double r = 4.0;
Circle circle = new Circle(r);
double rs1 = 4.0, rs2 = 6.0;
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Rectangle rectangle = new Rectangle(rs1, rs2);
Triangle triangle = new Triangle(ts1, ts2, ts3);
System.out.println("Radius of the Circle"+r);
System.out.println("Area of the Circle: " + circle.getArea());
System.out.println("Perimeter of the Circle: " + circle.getPerimeter());
System.out.println("\nSides of the rectangle are: "+rs1+','+rs2);
System.out.println("Area of the Rectangle: " + rectangle.getArea());
System.out.println("Perimeter of the Rectangle: " + rectangle.getPerimeter());
System.out.println("\nSides of the Traiangel are: "+ts1+','+ts2+','+ts3);
System.out.println("Area of the Triangle: " + triangle.getArea());
System.out.println("Perimeter of the Triangle: " + triangle.getPerimeter());
}
}
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345
Sides of the rectangle are: 4.0,6.0
Area of the Rectangle: 24.0
Perimeter of the Rectangle: 20.0
Sides of the Traiangel are: 3.0,4.0,5.0
Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0
案例 07
编写一个 Java 程序,创建一个带有 move()
和 makeSound()
方法的基类 Animal。创建两个子类 Bird 和 Panthera。在每个子类中覆盖 move()
方法,以描述每种动物如何移动。同时,覆盖每个子类中的 makeSound()
方法,为每种动物发出特定的声音。
//Animal.java
class Animal {
public void move() {
System.out.println("Animal moves");
}
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
//Bird.java
class Bird extends Animal {
@Override
public void move() {
System.out.println("Bird flies");
}
@Override
public void makeSound() {
System.out.println("Bird chirps");
}
}
//Panthera.java
class Panthera extends Animal {
@Override
public void move() {
System.out.println("Panthera walks");
}
@Override
public void makeSound() {
System.out.println("Panthera roars");
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Animal bird = new Bird();
Animal panthera = new Panthera();
performAction(bird);
performAction(panthera);
}
public static void performAction(Animal animal) {
animal.move();
animal.makeSound();
}
}
Bird flies
Bird chirps
Panthera walks
Panthera roars
案例 08
编写一个 Java 程序,创建一个带有 draw()
和 calculateArea()
方法的基类 Shape。创建三个子类: 圆形、正方形和三角形。覆盖每个子类中的 draw()
方法以绘制相应的形状,覆盖 calculateArea()
方法以计算并返回每个形状的面积。
//Shape.java
abstract class Shape {
public abstract void draw();
public abstract double calculateArea();
}
//Circle.java
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
//Square.java
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public void draw() {
System.out.println("Drawing a square");
}
@Override
public double calculateArea() {
return side * side;
}
}
//Triangle.java
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a triangle");
}
@Override
public double calculateArea() {
return 0.5 * base * height;
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(7.0);
Shape square = new Square(12.0);
Shape triangle = new Triangle(5.0, 3.0);
drawShapeAndCalculateArea(circle);
drawShapeAndCalculateArea(square);
drawShapeAndCalculateArea(triangle);
}
public static void drawShapeAndCalculateArea(Shape shape) {
shape.draw();
double area = shape.calculateArea();
System.out.println("Area: " + area);
}
}
Drawing a circle
Area: 153.93804002589985
Drawing a square
Area: 144.0
Drawing a triangle
Area: 7.5
案例 09
编写一个 Java 程序,创建一个带有 deposit()
和 withdraw()
方法的基类 BankAccount。创建两个子类 SavingsAccount 和 CheckingAccount。重写每个子类中的 withdraw()
方法,以规定不同的取款限额和费用。
//BankAccount.java
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds.");
}
}
}
//SavingsAccount.java
class SavingsAccount extends BankAccount {
private double withdrawalLimit;
public SavingsAccount(double initialBalance, double withdrawalLimit) {
super(initialBalance);
this.withdrawalLimit = withdrawalLimit;
}
@Override
public void withdraw(double amount) {
if (amount <= withdrawalLimit) {
super.withdraw(amount);
} else {
System.out.println("Withdrawal limit exceeded.");
}
}
}
//CheckingAccount.java
class CheckingAccount extends BankAccount {
private double overdraftFee;
public CheckingAccount(double initialBalance, double overdraftFee) {
super(initialBalance);
this.overdraftFee = overdraftFee;
}
@Override
public void withdraw(double amount) {
if (amount <= getBalance()) {
super.withdraw(amount);
} else {
System.out.println("Overdraft fee applied.");
super.withdraw(amount + overdraftFee);
}
}
}
//Main.java
public class Main {
public static void main(String[] args) {
BankAccount savingsAccount = new SavingsAccount(2000, 650);
BankAccount checkingAccount = new CheckingAccount(1000, 100);
withdrawFromAccount(savingsAccount, 300);
withdrawFromAccount(checkingAccount, 250);
System.out.println("Savings Account Balance: " + savingsAccount.getBalance());
System.out.println("Checking Account Balance: " + checkingAccount.getBalance());
}
public static void withdrawFromAccount(BankAccount account, double amount) {
account.withdraw(amount);
}
}
- BankAccount 类是基类,SavingsAccount 和 CheckingAccount 是其子类。每个子类都会重载
withdraw()
方法,以根据各自的特定规则设置不同的取款限额和费用。 - 在 Main 类中,我们有一个静态方法
withdrawFromAccount(BankAccount account, double amount)
,该方法将基类 BankAccount 的一个对象作为参数。在该方法中,我们调用了账户对象的withdraw()
方法。由于withdrawFromAccount
方法的参数是 BankAccount 类型,因此它可以接受 储蓄账户 和 支票账户 对象,这要归功于多态性。
Savings Account Balance: 1700.0
Checking Account Balance: 750.0
案例 10
编写一个 Java 程序,创建一个带有 eat()
和 sound()
方法的基类 Animal。创建三个子类: 狮子、老虎和豹。在每个子类中覆盖 eat()
方法,以描述每种动物吃什么。此外,覆盖 sound()
方法,为每种动物发出特定的声音。
//Animal.java
class Animal {
public void eat() {
System.out.println("Animal eats.");
}
public void sound() {
System.out.println("Animal makes a sound.");
}
}
//Lion.java
class Lion extends Animal {
@Override
public void eat() {
System.out.println("Lion eats meat.");
}
@Override
public void sound() {
System.out.println("Lion roars.");
}
}
//Tiger.java
class Tiger extends Animal {
@Override
public void eat() {
System.out.println("Tiger eats meat and sometimes fish.");
}
@Override
public void sound() {
System.out.println("Tiger growls.");
}
}
//Panther.java
class Panther extends Animal {
@Override
public void eat() {
System.out.println("Panther eats meat and small mammals.");
}
@Override
public void sound() {
System.out.println("Panther purrs and sometimes hisses.");
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Animal lion = new Lion();
Animal tiger = new Tiger();
Animal panther = new Panther();
lion.eat();
lion.sound();
tiger.eat();
tiger.sound();
panther.eat();
panther.sound();
}
}
Lion eats meat.
Lion roars.
Tiger eats meat and sometimes fish.
Tiger growls.
Panther eats meat and small mammals.
Panther purrs and sometimes hisses.
案例 11
编写一个 Java 程序,创建一个基类 Vehicle,其中包含 startEngine()
和 stopEngine()
方法。创建两个子类汽车和摩托车。在每个子类中重载 startEngine()
和 stopEngine()
方法,以不同的方式启动和停止发动机。
//Vehicle.java
abstract class Vehicle {
public abstract void startEngine();
public abstract void stopEngine();
}
//Car.java
class Car extends Vehicle {
@Override
public void startEngine() {
System.out.println("Car engine started with a key.");
}
@Override
public void stopEngine() {
System.out.println("Car engine stopped when the key was turned off.");
}
}
//Motorcycle.java
class Motorcycle extends Vehicle {
@Override
public void startEngine() {
System.out.println("Motorcycle engine started with a kick-start.");
}
@Override
public void stopEngine() {
System.out.println("Motorcycle engine stopped when ignition was turned off.");
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle motorcycle = new Motorcycle();
startAndStopEngine(car);
startAndStopEngine(motorcycle);
}
public static void startAndStopEngine(Vehicle vehicle) {
vehicle.startEngine();
vehicle.stopEngine();
}
}
Car engine started with a key.
Car engine stopped when the key was turned off.
Motorcycle engine started with a kick-start.
Motorcycle engine stopped when ignition was turned off.
案例 12
编写一个 Java 程序,创建一个带有 draw()
和 calculateArea()
方法的基类 Shape。创建两个子类 Circle 和 Cylinder。在每个子类中覆盖 draw()
方法,以绘制相应的形状。此外,在 Cylinder 子类中重载 calculateArea()
方法,以计算并返回圆柱体的总表面积。
//Shape.java
abstract class Shape {
public abstract void draw();
public abstract double calculateArea();
}
//Circle.java
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
protected double getRadius() {
return radius;
}
}
//Cylinder.java
class Cylinder extends Circle {
private double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a cylinder");
}
@Override
public double calculateArea() {
// Calculate the total surface area of the cylinder (including the circular top and bottom)
double circleArea = super.calculateArea();
double sideArea = 2 * Math.PI * getRadius() * height;
return 2 * circleArea + sideArea;
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(7.0);
Shape cylinder = new Cylinder(4.0, 9.0);
drawShapeAndCalculateArea(circle);
drawShapeAndCalculateArea(cylinder);
}
public static void drawShapeAndCalculateArea(Shape shape) {
shape.draw();
double area = shape.calculateArea();
System.out.println("Area: " + area);
}
}
Drawing a circle
Area: 153.93804002589985
Drawing a cylinder
Area: 326.7256359733385