Java 中override、overload、overwrite区别,以及与多态的关系【转】

因为早期的翻译导致了override和overwrite的解释及理解混乱,需要重新梳理这几个词及相关内容。

转自:http://blog.csdn.net/lzhang007/article/details/7960950

一  

overload:重载的意思,这没啥能混淆的了,就是在同一个类当中,为了增加通用性,写了很多方法,这些方法只有一个要求,参数的数量和类型不同,但返回值和方法属性必须相同,否则不属于重载,

比如:1.public class Parent{

                                                                           public int add(int a, int b){}

                                                                           public int add(int a,float b){}

                                                                           public int add(int a,int b,float c){}

                                                                            以上均属于overload 

                                                                            protected int add(int a,float b){}

                                                                             public float add(int a,float b){}   }(注意:java中明确声明在同一个类中两个方法名字和参数相同而返回值不同是不被允许的

                                                                 public class Child extends Parent{

                                                                             public int add(int a,float b){}(这种在The Java™ Tutorial Fourth Edition中也称作overload但是跟superclass中的同名方法是两种完全不同的方法)

                                                                                                                               }

                                                                              均不属于overload

参考:http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

提示:Note: Overloaded methods should be used sparingly, as they can make code much less readable.

它不决定java的多态

override有人翻译是重写,有人翻译是覆写,覆盖等。其实我认为是一种扩展

因为它是在父类中声明方法(一般是抽象的),在子类中根据需求去具体定义方法的行为(即modify behavior as needed)

它要求override的方法有相同的名字、相同的参数、相同的返回值类型(即the same name, number and type of parameters, and return type

它是一种晚绑定,是决定java多态的一种方式

参考:http://docs.oracle.com/javase/tutorial/java/IandI/override.html

 

overwrite:java中就没有它的存在,就别以讹传讹了,java官方文档没有该词的出现,但是国外有人把overwrite解释为override,

比如:http://stackoverflow.com/questions/837864/java-overloading-vs-overwriting

Overriding, which is what I think you mean by "overwriting" is the act of providing a different implementation of a method inherited from a base type, and is basically the point of polymorphism by inheritance, i.e.

public class Bicycle implements Vehicle {
    public void drive() { ... }
}

public class Motorcycle extends Bicycle {
    public void drive() {
        // Do motorcycle-specific driving here, overriding Bicycle.drive()
        // (we can still call the base method if it's useful to us here)
    }
}

posted on 2013-07-18 14:02  在旅途  阅读(1468)  评论(0编辑  收藏  举报

导航