多态是面向对象的三大特征之一
谈到多态,不得不提的就是,多态中的成员绑定问题.
方法绑定
将一个方法调用同一个方法主体关联起来被称为绑定.若在程序执行前进行绑定(如果有的话,由编译器和连接程序实现),叫做前期绑定.在运行时根据对象的类型进行绑定,称为后期绑定,也称为动态绑定或者运行时绑定.
Java中除了static方法和final方法(private方法属于final方法)之外,其他所有的方法都是后期绑定.
public class Shape {
public void draw() {
System.out.println("Shape draw.");
}
public void erase() {
System.out.println("Shape erase");
}
}
public class Circle extends Shape {
public void draw() {
System.out.println("Circle draw.");
}
public void erase() {
System.out.println("Circle erase.");
}
}
public class Shapes {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
}
}
//output
Circle draw.
缺陷:"覆盖"私有方法
public class PrivateOverride {
private void f(){
System.out.println("private f()");
}
public static void main(String[] args){
PrivateOverride privateOverride = new Derived();
privateOverride.f();
}
}
class Derived extends PrivateOverride{
public void f(){
System.out.println("public f()");
}
}
//output
private f()
我们期望的输出是public f(),但是由于private方法被自动认为是final方法,而且对导出类(子类)是屏蔽的.因此,在这种情况下,Derived类中的f()方法就是一个全新的方法,既然基类中的f()方法在子类Derived中不可见,因此甚至也不能被重载.
缺陷:域与静态方法
如果你直接访问某个域,这个访问就将在编译期进行解析,就像下面的示例所演示的:
class Super {
public int field = 0;
public int getField() {
return field;
}
}
class Sub extends Super {
public int field = 1;
public int getField() {
return field;
}
public int getSuperField() {
return super.field;
}
}
public class FieldAccess {
public static void main(String[] args) {
Super sup = new Sub();
System.out.println("sup.field = " + sup.field + ", sup.getField() = " + sup.getField());
Sub sub = new Sub();
System.out.println("sub.field = " + sub.field + ", sub.getField() = " + sub.getField());
System.out.println("sub.getSuperField() = " + sub.getSuperField());
}
}
//output
sup.field = 0, sup.getField() = 1
sub.field = 1, sub.getField() = 1
sub.getSuperField() = 0
当Sub对象转型为Super引用时,任何域访问操作都将由编译器解析,因此不是多态的.在本例中,为Super.field和Sub.field分配了不同的存储空间.这样,Sub实际上包含了两个称为field的域:它自己的和它从Super处得到的.然而,在引用Sub中的field时产生的默认域并非Super版本的field域.
如果某个方法是静态的,它的行为就不具有多态性:
class StaticSuper {
public static String staticGet() {
return "Base staticGet()";
}
public String dynamicGet() {
return "Base dynamicGet()";
}
}
class StaticSub extends StaticSuper {
public static String staticGet() {
return "Derived staticGet()";
}
public String dynamicGet() {
return "Derived dynamicGet()";
}
}
public class StaticPolymorphism {
public static void main(String[] args) {
StaticSuper sup = new StaticSub();
System.out.println(sup.staticGet());
System.out.println(sup.dynamicGet());
}
}
//outp
Base staticGet()
Derived dynamicGet()