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
Ais initialized: its instance variablesiis set to2,jis set to5. - Class
Ddoesn’t define its owniorj, so it inherits these values directly fromA. At this point, theDobject hasi=2andj=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’si(inherited fromA, value is2).super.j: Refers explicitly to thejvariable in the superclassA(value is5).- So
this.j = 2 + 5 = 7. Theivariable remains unchanged at2.
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’ssetusesint jandD’s usesint 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
Ddoesn’t declare its owniorj, accessinga.ianda.jrefers to the inherited values fromA, which align with the object’s actual state here.
内容的提问来源于stack exchange,提问作者Salvatore Danilo Palumbo
相关产品推荐
相关产品推荐

