子类覆写(Override)父类的方法,意味着在该子类对象上调用该方法时,始终调用的是其子类的实现,不管使用的是它父类的引用还是其子类的引用。(
When you invoke a method through an object reference, the actual class of the object governs which implementation is used.)
Overriding a method means that you have replaced its implementation so that when the method is invoked on an object of the subclass, it is the subclass's version of the method that gets invoked.
仍然使用上篇文章的代码示例:ExtendingClass ---> SuperClass
在构造SuperClass时调用了update()方法,此时实际运行的是子类的update()方法,由于此时子类的属性仅分配了内存,并没有被初始化(str=null),所有打印的结果为:update in child null
Overriding a method means that you have replaced its implementation so that when the method is invoked on an object of the subclass, it is the subclass's version of the method that gets invoked.
仍然使用上篇文章的代码示例:ExtendingClass ---> SuperClass
在构造SuperClass时调用了update()方法,此时实际运行的是子类的update()方法,由于此时子类的属性仅分配了内存,并没有被初始化(str=null),所有打印的结果为:update in child null
- 覆写方法时可以修改方法的访问修饰符,但是仅能扩大父类中该方法的访问权限。例如:protected -> public
- 可以修改方法的返回值类型,但是只能是父类中该方法的返回值类型的子类。
- 可以修改方法的其他属性synchronized, native, 和 strictfp(The synchronized, native, and strictfp modifiers can be freely varied because they are implementation concerns)
- 可以修改方法的throws语句,但是所有子类抛出的异常类型必须是与父类中抛出的异常具有相同的类型或者是其子类。子类的方法throws语句中的异常个数可以少于父类中声明的个数,甚至可以没有throws语句,此时意味着子类方法将可能抛出no checked exceptions。
- 覆写方法不能修改方法的签名,即不能修改方法名和参数的个数及类型。但是能够改变方法的参数是否为final