向void方法传参(整数/对象):代码第3、7行输出结果疑惑咨询
Hey there! Let's break down why lines 3 and 7 have the expected outputs of 20 and 35 respectively, instead of the 25 and 40 you calculated. First, let's recap the key details you provided:
- Expected full output:
1 : 10 2 : 20 3 : 20 4 : 15 5 : 40 6 : 75 7 : 35 8 : 75 9 : 20 - Your results: Line 3 =
25, Line 7 =40
Since your code snippet cuts off at public class Alpha { protected i..., I'll base this explanation on the most common Java scenarios that lead to these kinds of discrepancies—they almost always tie to inheritance behavior, variable scoping, or execution order.
Line 3: Why 20 instead of 25?
The most likely culprit here is member variable hiding in an inheritance hierarchy. Let's say your code follows a super common pattern for this type of question:
public class Alpha { protected int num = 10; public void updateValue() { num += 10; // Updates parent's num to 20 } } public class Bravo extends Alpha { protected int num = 15; // This HIDES the parent's num variable @Override public void updateValue() { num += 10; // Updates child's num to 25 } }
If line 3's output comes from accessing the parent class's num variable (not the child's), you'll get 20 instead of 25. Java doesn't "override" member variables like it does methods—parent and child variables with the same name are completely separate. If the code uses a parent class reference to call updateValue() (or directly accesses the parent's variable via super.num), it'll use the parent's value, not the child's.
Another possibility is execution order: maybe you assumed a calculation like 10 + 15 was happening, but the actual code first adds 10 to the initial 10 (resulting in 20) before any other operations.
Line 7: Why 35 instead of 40?
This is almost certainly about sequential variable modifications or a method's return logic that you overlooked. For example:
- Maybe after line 6's output of 75, the code performs a subtraction:
75 - 40 = 35 - Or a variable you thought was set to 40 gets adjusted with
-5before line 7's output:40 - 5 = 35 - If inheritance is involved again, an overridden method in the parent class might return a value that's 5 less than the child's method (e.g., parent returns
num -5while child returnsnum).
Here's a quick example of how this might play out:
public int getLine7Value() { int currentValue = 40; currentValue -= 5; // Adjusts to 35 before returning return currentValue; }
If you missed that final subtraction step, you'd naturally expect 40 instead of the actual 35.
If you can share the full code snippet, I can give you an even more precise breakdown—but based on the most common Java pitfalls that cause these exact mismatches, these explanations should align with what's happening in your code.
内容的提问来源于stack exchange,提问作者dragi

