多态:
通俗的说,多态是由于继承结构的存在一个类有多个导出类,表现的出多种行为;
具体的讲,多态就是将导出类看做是它的基类,通过动态绑定,实现多种不同的行为。
- 向上转型
将导出类看做是它的基类的过程称为向上转型(upcasting)
void doSomethings(Shape shape) {
shape.erase();
shape.draw();
}
Circle circle = new Circle();
Triangle triangle = new Triangle();
Line line = new Line();
doSomethings(circle);
doSomethings(triangle);
doSomethings(line);
1.只有非private方法才能被覆盖,private方法不具有多态性;
2.静态方法不具有多态性。
3.编写构造器时有一条有效的准则:“用尽可能简单的方法使对象进入正常状态,如果可以的话,避免调用其他方法”,在构造器内部唯一能够安全的调用的那些方法是基类中的final方法(也适用于private方法,它们自动属于final)。
- 向下转型
向下转型是不安全的。
class Useful {
public void f() {
}
public void g() {
}
}
class MoreUseful extends Useful {
@Override
public void f() {
}
public void g() {
}
public void u() {
}
public void v() {
}
public void w() {
}
}
/**
* @Author ZhangGJ
* @Date 2020/11/16 08:28
*/
public class RTTI {
public static void main(String[] args) {
Useful[] x = {new Useful(), new MoreUseful()};
x[0].f();
x[1].g();
// Compile time: method not found in Useful:
// x[1].u();
/**
* Downcast/RTTI
*/
((MoreUseful) x[1]).u();
/**
* Exception thrown
*/
((MoreUseful) x[0]).u();
}
}