在Java中覆盖vs阴影

时间:2013-06-17 17:41:50

标签: java

特别是对于此声明,重写和阴影之间有什么区别 “静态方法不能在子类中重写,只能被遮蔽”

2 个答案:

答案 0 :(得分:4)

如果你真的覆盖了一个方法,你可以在它的某个位置调用super()来调用超类实现。但由于static方法属于一个类,而不是一个实例,因此只能通过提供具有相同签名的方法来“遮蔽”它们。任何类型的静态成员都不能被继承,因为它们必须通过类访问。

答案 1 :(得分:1)

重写...这个术语指的是例如

的多态行为
class A {
   method(){...} // method in A
}

class B extends A {
    @Override
    method(){...} // method in B with diff impl.
}

当您尝试从B类调用该方法时,您将获得覆盖behvaior ..e.g

A myA = new B();
myB.method();   // this will print the content of from overriden method as its polymorphic behavior

但是假设您使用静态修饰符声明了方法,而不是尝试使用相同的代码

A myA = new B();
myA.method();  // this will print the content of the method from the class A

这是因为静态方法无法覆盖... B类中的方法只是从A类中隐藏方法...