java - 当在子类中声明一个父类中存在的变量后,自动调用的父类构造函数不起作用。
高洛峰
高洛峰 2017-04-18 10:46:33
0
3
551
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
左手右手慢动作

The execution sequence is as follows:

1. super();
1.1. super.i = 7;
1.2. this.setI(20) => this.i = 60;
1.3. System.out.println("i from a is " + super.i) => 7;
2. this();
2.1. this.i = 10;
2.2. System.out.println("i from b is " + this.i) => 10;
  • A.iB.i 都是package-private的, B.i 没有Override A.i, the two are independent;

  • A.setIB.setI 都是public, B.setI Override A.setI, A在构造时调用的是B.setI;

  • B’s members outside the constructor are initialized in super()之后执行的, B.i先是在super里被B.setI and set to 60, and then B’s members are initialized to 10;


Delete int i = 10;之后, 如果A和B处于同一个package, B.setI访问的就是A.i in B. When super() is used, A.i is set to 60 and there will be no change. Both prints are 60

黄舟

If I declare a member in the subclass that already exists in the parent class, will there be no error? It should at least be a warning.

I can only say that the question is too wicked. It is impossible to write like this in actual development. You will dig a hole for yourself.

Ty80

7.10
1. Go to the construction method of A and complete the empty parameter construction of Object.
2.int I=7
3.setI(20) calls the setI() of the subclass. At this time, the I of the subclass is 60, and the I of the parent class is still 7.
4. Print this.i. At this time, in the parent class In the class, it is 7; (note: the variable depends on the actual caller, this is the current parent class; the method is overridden and calls the subclass)
5.int I=10 covers the original 60.
6, print this .i is 10 at this time.

60.60
Note: If you delete the I of the subclass, the I of the parent class is called by default
3. Call the setI of the subclass and assign it to the parent class. At this time, the parent class changes to 60.
5. There is no coverage at this time , this.i calls the I inherited from the parent class by default, which is 60.

On the importance of Degbug...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template