What is polymorphic method in java?(java中的多态方法是什么?)
问题描述
请在 Java 的上下文中解释什么是多态方法".
In the context of Java, please explain what a "polymorphic method" is.
推荐答案
多态"的意思是多种形状".在 Java 中,您可以拥有一个超类,其子类使用相同的名称来做不同的事情.传统的例子是超类 Shape
,子类 Circle
、Square
和 Rectangle
,以及方法 area()
.
"Polymorphic" means "many shapes." In Java, you can have a superclass with subclasses that do different things, using the same name. The traditional example is superclass Shape
, with subclasses Circle
, Square
, and Rectangle
, and method area()
.
所以,例如
// note code is abbreviated, this is just for explanation
class Shape {
public int area(); // no implementation, this is abstract
}
class Circle {
private int radius;
public Circle(int r){ radius = r ; }
public int area(){ return Math.PI*radius*radius ; }
}
class Square {
private int wid;
Public Square(int w){ wid=w; }
public int area() { return wid*wid; }
}
现在考虑一个例子
Shape s[] = new Shape[2];
s[0] = new Circle(10);
s[1] = new Square(10);
System.out.println("Area of s[0] "+s[0].area());
System.out.println("Area of s[1] "+s[1].area());
s[0].area()
调用Circle.area()
,s[1].area()
调用Square.area()
-- 因此我们说 Shape
及其子类利用对方法区域的多态调用.
s[0].area()
calls Circle.area()
, s[1].area()
calls Square.area()
-- and thus we say that Shape
and its subclasses exploit polymorphic calls to the method area.
这篇关于java中的多态方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java中的多态方法是什么?


- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01