什么是java中的多态方法? [英] What is polymorphic method in java?
问题描述
我正在学习SCJP测试的java语言。
I'm studying java language for SCJP test.
理解多态方法有点难。
你能为我解释一下吗?
或给我一些链接?
Could you explain it for me? or give me some links?
推荐答案
多态意味着很多形状。在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中的多态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!