You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java代码执行结果咨询:为何输出为9?

Explanation of the Java Code Outputting 9

Let’s break down exactly what happens step by step to arrive at the output of 9:

1. Object Initialization

When we create new D() in the main method:

  • First, the superclass A is initialized: its instance variables i is set to 2, j is set to 5.
  • Class D doesn’t define its own i or j, so it inherits these values directly from A. At this point, the D object has i=2 and j=5.

2. Polymorphic Method Call

The line a.set(5) leverages polymorphism: even though the reference a is typed as A, the actual object instance is D. Java uses dynamic dispatch here, meaning it executes the set method defined in D, not the one in A.

3. Executing D’s set Method

Let’s look closely at D’s overridden set method:

@Override void set (int i) { this.j = this.i + super.j; }
  • this.i: Refers to the instance’s i (inherited from A, value is 2).
  • super.j: Refers explicitly to the j variable in the superclass A (value is 5).
  • So this.j = 2 + 5 = 7. The i variable remains unchanged at 2.

4. Calculating the Final Output

After calling set(5), the object’s state is i=2 and j=7. The line System.out.println(a.i + a.j) adds these two values: 2 + 7 = 9.

Key reminders:

  • Method overriding depends on the method signature (name and parameter types), not parameter names. Even though A’s set uses int j and D’s uses int i, they’re still overridden because the parameter type matches.
  • Instance variables are not polymorphic—they’re resolved at compile time based on the reference type. Since D doesn’t declare its own i or j, accessing a.i and a.j refers to the inherited values from A, which align with the object’s actual state here.

内容的提问来源于stack exchange,提问作者Salvatore Danilo Palumbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:11:36