thinking in java3中的多态
People are often confused by other, non-object-oriented features of Java, like method overloading, which are sometimes presented as object-oriented. Don’t be fooled: If it isn’t late binding, it isn’t polymorphism
多态:就是指相同的事物的不同状态,比如:水。水可以有三种状态:
气体、液体和固体。那么在JAVA中的多态也可以理解成这个意思,就是:
将父对象设置成为和一个或多个它的子对象相等的技术,
比如Parent=Child;
多态性使得能够利用同一类(父类)引用不同类的对象,
以及根据所引用对象的不同,以不同的方式执行相同的操作。
多态实现包括两种方式:重载和重写
例如:Animal a = new Tiger(); 这是一个老话题了,呵呵……
父类引用指向子类对象,Animal类中包含一个eat()方法,而Tiger类继承自
Animal类,如果子类重写了父类的eat()方法,则调用的时候,就可以按照子类
的形式调用,本质上是父类的方法,但是子类重写之后,就成了另一种方式,
People are often confused by other, non-object-oriented features of Java, like method overloading, which are sometimes presented as object-oriented. Don’t be fooled: If it isn’t late binding, it isn’t polymorphism
按文面翻译
人们总是被Java的另一种非面向对象的特性所困惑,就像方法重载,有时候它以面向对象而存在,请不要犯傻,如果没有后期绑定(也就是运行期的动态绑定),它就不是多态.
所以,这段话要表达的意思就是说,多态要有动态绑定,否则就不是多态,方法重载也不是多态(因为方法重载是编译期决定好的,没有后期也就是运行期的动态绑定)
当满足这三个条件 1.有继承 2. 有重写 3. 要有父类引用指向子类对象
- <span style="font-size:14px;">
- 例:
- public class Address {
- private String name;
- public Address(String name){
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- 定义基类(抽象类):
- public abstract class Vehicle {
- abstract void go(Address address);
- }
- Car对于基类的实现:
- public class Car extends Vehicle{
- @Override
- public void go(Address address){
- System.out.println("Car to " + address.getName());
- }
- }
- Plane对于基类的实现:
- public class Plane extends Vehicle{
- @Override
- void go(Address address) {
- System.out.println("Plane to " + address.getName());
- }
- }
- Driver中多态:
- public void drive(Vehicle v){ ///多态,父类引用指向子类对象,实际传过来的是抽象类Vehicle的子类,或者实现类,然后编译器会根据具体实现类,来找实现方法。
- v.go(new Address("杭州(abstract)")); ///此方法在具体的实现中被重写
- }
- Test:
- public static void main(String[] args) {
- Driver d = new Driver();
- d.drive(new Plane()); //实际是Plane对象,则编译器就会找到Plane中,对go的实现
- d.drive(new Car()); //实际是Car对象,则编译器就会找到Plane中,对go的实现
- }
- 输出结果:
- Plane to 杭州(abstract)
- Car to 杭州(abstract)
- </span>
多态:就是指相同的事物的不同状态,比如:水。水可以有三种状态:
气体、液体和固体。那么在JAVA中的多态也可以理解成这个意思,就是:
将父对象设置成为和一个或多个它的子对象相等的技术,
比如Parent=Child;
多态性使得能够利用同一类(父类)引用不同类的对象,
以及根据所引用对象的不同,以不同的方式执行相同的操作。
多态实现包括两种方式:重载和重写
例如:Animal a = new Tiger(); 这是一个老话题了,呵呵……
父类引用指向子类对象,Animal类中包含一个eat()方法,而Tiger类继承自
Animal类,如果子类重写了父类的eat()方法,则调用的时候,就可以按照子类
的形式调用,本质上是父类的方法,但是子类重写之后,就成了另一种方式,
这就是多态。
http://blog.csdn.net/u012110719/article/details/48497085