我不知道覆盖与隐藏在Java中有什么不同。有谁能提供更多关于这些差异的细节吗?我读过Java教程,但是示例代码仍然让我感到困惑。
更清楚的是,我很理解压倒一切。我的问题是,我不认为隐藏有什么不同,除了一个在实例级别,而另一个在类级别。
查看Java教程代码:
public class Animal {
public static void testClassMethod() {
System.out.println("Class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("Instance " + " method in Animal.");
}
}然后我们有一个子类Cat
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}然后他们说:
该程序的输出如下: 动物类方法。 Cat中的实例方法。
对我来说,直接从testClassMethod()类调用类方法Animal执行Animal类中的方法这一事实非常明显,没有什么特别之处。然后,他们从对myCat的引用中调用myCat,因此非常明显的是,执行的方法就是Cat实例中的方法。
据我所见,调用隐藏的行为就像重写一样,那么为什么要做出这种区分呢?如果我使用上面的类运行这段代码:
Cat.testClassMethod();我会得到:猫的类方法。但是,如果我从猫中删除testClassMethod(),那么我将得到:动物中的类方法。
这向我展示了在子类中使用与父类相同的签名来编写一个静态方法,这在很大程度上起到了覆盖作用。
希望我能弄清楚我在哪里困惑,有人能给我一些启示。非常感谢提前!
发布于 2012-05-15 04:21:58
覆盖基本上支持后期绑定。因此,在运行时将决定调用哪个方法。它适用于非静态方法.
隐藏用于所有其他成员(静态方法、实例成员、静态成员)。它的基础是早期绑定。更清楚的是,要调用或使用的方法或成员是在编译期间决定的。
在您的示例中,第一个调用,Animal.testClassMethod()是对static方法的调用,因此非常确定将调用哪个方法。
在第二个调用myAnimal.testInstanceMethod()中,您将调用一个非静态方法。这就是所谓的运行时多态性。直到运行时才决定要调用哪种方法。
有关进一步的澄清,请阅读覆盖Vs隐藏。
发布于 2012-05-15 04:28:22
静态方法是隐藏的,非静态方法是多余的.当调用没有限定为“The ()”与"this.something()“时,两者之间的区别是显著的。
我似乎不能把它写在文字上,所以这里有一个例子:
public class Animal {
public static void something() {
System.out.println("animal.something");
}
public void eat() {
System.out.println("animal.eat");
}
public Animal() {
// This will always call Animal.something(), since it can't be overriden, because it is static.
something();
// This will call the eat() defined in overriding classes.
eat();
}
}
public class Dog extends Animal {
public static void something() {
// This method merely hides Animal.something(), making it uncallable, but does not override it, or alter calls to it in any way.
System.out.println("dog.something");
}
public void eat() {
// This method overrides eat(), and will affect calls to eat()
System.out.println("dog.eat");
}
public Dog() {
super();
}
public static void main(String[] args) {
new Dog();
}
}产出:
animal.something
dog.eat发布于 2012-05-15 04:25:32
这就是覆盖和隐藏的区别,

https://stackoverflow.com/questions/10594052
复制相似问题