A question that puzzles me for a long time

Source: Internet
Author: User

A question that puzzles me for a long time

The following code:

Package com. lk. c; public class Test5 {public static void main (String [] args) {go (new MyBase ();} static void go (Base B) {B. add (8) ;}} class Base {int I; Base () {add (1); System. out. println (I);} void add (int v) {I = I + v; System. out. println (I);} void print () {System. out. println (I) ;}} class MyBase extends Base {MyBase () {add (2);} void add (int v) {I ++ = v * 2; System. out. println (I );}}
22622

A beginner in Java. I hope someone can answer the following questions:

After debugging, the sequence is as follows: when the add (1) method in the constructor of the parent class is used, why not call the add () method of the parent class, and the add () method of the subclass is called? Therefore, the first output is 2.

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.