【发布时间】:2010-01-12 09:13:07
【问题描述】:
覆盖和重载有什么区别?
【问题讨论】:
-
在 Java 术语中,通常使用“方法”而不是“函数”。
-
对不起,我正在努力学习,谢谢您的指正,我将从现在开始使用函数
-
-1 把这个问题输入谷歌,你就会得到成千上万的解释。
标签: java overloading overriding
覆盖和重载有什么区别?
【问题讨论】:
标签: java overloading overriding
重载:在编译时根据指定参数的数量和类型选择方法签名
覆盖:在执行时根据目标对象的实际类型(相对于表达式的编译时类型)选择方法实现
李>例如:
class Base
{
void foo(int x)
{
System.out.println("Base.foo(int)");
}
void foo(double d)
{
System.out.println("Base.foo(double)");
}
}
class Child extends Base
{
@Override void foo (int x)
{
System.out.println("Child.foo(int)");
}
}
...
Base b = new Child();
b.foo(10); // Prints Child.foo(int)
b.foo(5.0); // Prints Base.foo(double)
这两个调用都是重载的例子。有两个方法叫做foo,编译器决定调用哪个签名。
第一次调用是一个覆盖的例子。编译器选择签名“foo(int)”,但在执行时,目标对象的类型决定了要使用的实现应该是 Child 中的那个。
【讨论】:
方法重载是一种编译器技巧,它允许您使用相同的名称根据参数执行不同的操作。
覆盖一个方法意味着它的全部功能都被替换了。覆盖是在子类中对父类中定义的方法进行的操作。
【讨论】:
重载:
public Bar foo(int some);
public Bar foo(int some, boolean x); // Same method name, different signature.
覆盖:
public Bar foo(int some); // Defined in some class A
public Bar foo(int some); // Same method name and signature. Defined in subclass of A.
如果没有定义第二种方法,它将继承第一种方法。现在它将被A的子类中的第二个方法替换。
【讨论】:
重载 - 相似的签名 - 相同的名称,不同的参数
void foo() {
/** overload */
}
void foo( int a ) {
/** overload */
}
int foo() {
/** this is NOT overloading, signature is for compiler SAME like void foo() */
}
覆盖 - 您可以在继承时重新定义方法主体。
class A {
void foo() {
/** definition A */
}
}
class B extends A {
void foo() {
/** definition B, this definition will be used when you have instance of B */
}
}
【讨论】:
关于有趣的事情要提:
public static doSomething(Collection<?> c) {
// do something
}
public static doSomething(ArrayList<?> l) {
// do something
}
public static void main(String[] args) {
Collection<String> c = new ArrayList<String> ();
doSomething(c); // which method get's called?
}
有人会假设会调用带有 ArrayList 参数的方法,但实际上并没有。第一个方法被调用,因为在编译时选择了正确的方法。
【讨论】:
子类从超类继承的方法在子类中被替换(覆盖)。
class A {
void foo() {
/** definition A of foo */
}
}
class B extends A {
void foo() {
/** definition B of foo */
}
}
现在,如果您使用以下方式致电 foo:
A a = new B();
a.foo();
将运行foo 的B 定义。这不是那么直观,因为如果类A 没有名为foo 的方法,则会出现编译错误。所以a对象A的type必须有foo的方法,然后才能调用它,instance的方法foo em> 将被执行,这是 B 的类,因此是“执行时间”。
当您创建与现有方法同名的方法时。为了避免编译时错误,您必须使用与现有参数不同的参数来定义新方法。这样,这些方法将是可区分的。有一个名称和参数相同的方法,但不同的返回类型仍然是模糊的,因此会导致编译错误。重载示例:
class A {
void bar(int i) {}
// The following method is overloading the method bar
void bar(Object a) {}
// The following will cause a compile error.
// Parameters should differ for valid overload
boolean bar(int i) {
return true;
}
}
【讨论】: