Deepen the understanding of Java overriding parent class methods

Source: Internet
Author: User

1. About subclass methods overriding the parent class method follows the rule of "two and two small and one big"

Two identical: (1) method name (2) formal parameter list

Two small: (1) Subclass the return value type is smaller than the parent class or equal (2) the exception thrown by the subclass declaration should be smaller or equal than the parent class

One large: (1) Subclass permissions are larger or equal than the parent class

The above rules are easy to understand:

It is important to note how to understand that the subclass return type is smaller or equal than the parent class.

I believe a lot of beginners, like me, will understand that the scope of int is smaller than the long range, then whether you can override the parent class method, the original parent method return value long to int?

The answer is: No.

Cause: The return value type is smaller than the parent class, the return value type must be a parent-child relationship , and there is no parent-child relationship between the basic types.

The following is a code example: ( Note that student is a subclass of person)

Class A {
Public Person Test (int x) {
return null;
}
}

Class B extends A {
Public Student Test (int x) {
return null;
}
}

Class Person {

}

Class Student extends Person {

}

Deepen the understanding of Java overriding parent class methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.