gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
多态编程的例子
- User
多态编程的例子
- Assistant
- 动态绑定: 假设有一个父类Animal和两个子类Dog和Cat,它们都有一个方法makeSound()。在使用多态编程时,可以声明一个Animal类型的变量,然后通过动态绑定来调用makeSound()方法,具体调用哪个子类的方法取决于运行时对象的类型。
class Animal { public void makeSound() { System.out.println("Animal is making a sound"); } } class Dog extends Animal { public void makeSound() { System.out.println("Dog is barking"); } } class Cat extends Animal { public void makeSound() { System.out.println("Cat is meowing"); } } public class Main { public static void main(String[] args) { Animal animal = new Dog(); animal.makeSound(); // 输出:Dog is barking animal = new Cat(); animal.makeSound(); // 输出:Cat is meowing } }- 方法重写: 多态编程还可以通过子类重写父类的方法来实现不同的行为。假设有一个父类Shape和两个子类Circle和Rectangle,它们都有一个计算面积的方法getArea(),具体实现各自的计算公式。
class Shape { public double getArea() { return 0.0; } } class Circle extends Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } } class Rectangle extends Shape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } public double getArea() { return length * width; } } public class Main { public static void main(String[] args) { Shape shape = new Circle(5.0); System.out.println("Circle area: " + shape.getArea()); // 输出:Circle area: 78.53981633974483 shape = new Rectangle(4.0, 5.0); System.out.println("Rectangle area: " + shape.getArea()); // 输出:Rectangle area: 20.0 } }在上述例子中,通过声明Shape类型的变量,并通过动态绑定调用不同子类的getArea()方法,实现了多态性。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.