Method Overriding[叫做 覆盖 或 重写 或覆写] in Java _2(使用规则)

来源:互联网 发布:java基础入门怎么样 编辑:程序博客网 时间:2024/06/05 08:59

1. In object oriented terms, Overriding means to override the functionality of any existing method. 只能重写方法,不能重写成员变量这种说法。


Q:Why we are not able to override a instance variable of a super class in subclass?

A:Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).


2.Rules for method overriding:

  • The argument list should be exactly the same as that of the overridden method.

  • The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.

  • The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.

  • Instance methods can be overridden only if they are inherited by the subclass.

  • A method declared final cannot be overridden.

  • A method declared static cannot be overridden but can be re-declared.

  • If a method cannot be inherited then it cannot be overridden.

  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.

  • A subclass in a different package can only override the non-final methods declared public or protected.

  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overridden method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

  • Constructors cannot be overridden.



MORE:

http://www.tutorialspoint.com/java/java_overriding.htm

http://stackoverflow.com/questions/427756/overriding-a-super-class-instance-variables

http://www.javabeginner.com/learn-java/java-method-overriding


原创粉丝点击