您的位置:首页 > 其它

子类重写和隐藏父类的成员方法(Overriding and Hiding Methods)

2015-04-24 15:54 381 查看
先看一个例子:
public class Animal {public static void testClassMethod() {System.out.println("The static method in Animal");}public void testInstanceMethod() {System.out.println("The instance method in Animal");}}
</pre><pre name="code" class="html">public class Cat extends Animal {public static void testClassMethod() {System.out.println("The static 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();}}
the output:The static method in AnimalThe instance method in CatHere, The 
Cat
 classoverrides the instance method in 
Animal
 and hidesthe static method in 
Animal
. The 
main
 methodin this class creates an instance of 
Cat
 and invokes
testClassMethod()
 onthe class and 
testInstanceMethod()
 on the instance.Summary:

Instance Methods

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclassoverrides thesuperclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding methodhas the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.

Static Methods

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.The distinction between hiding a static method and overriding an instance method has important implications:The version of the overridden instance method that gets invoked is the one in the subclass.The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐