Could you please explain why is this output class TestApples
Could you please explain why is this output:
class TestApplesC
{
public static void main (String [] args)
{
AppleTree app = new AppleTree();
app.grow();
app.drop();
app.report();
}
}
class AppleTree
{
int apples = 53;
public void drop()
{
int apples = 11;
System.out.println(\"drop sees: \" + apples);
}
public void grow()
{
apples = 70;
System.out.println(\"grow sees: \" + apples);
}
public void report()
{
System.out.println(\"apples: \" + apples);
}
}
1)
Output:
grow sees: 70
drop sees: 11
apples: 70
|
Solution
Answer: when we run this class TestApplesC, it will invoke main method.
Inside main method, we created an object of AppleTree class.
AppleTree app = new AppleTree();
By using AppleTree object app , we are calling three method one by one.
app.grow();
app.drop();
app.report();
when we call grow() method by AppleTree object app.grow();
grow() method in AppleTree class will invoke and execute the statements written inside it.
in grow() method, we assigned value 70 to apples global variable so this statement System.out.println(\"grow sees: \" + apples); will print grow sees: 70
when we call drop () method by AppleTree object app.drop ();
drop () method in AppleTree class will invoke and execute the statements written inside it.
in drop () method, we assigned value 11 to apples local variable so this statement System.out.println(\"drop sees: \" + apples); will print drop sees: 11 but no changes happed to global apples variable.
when we call report() method by AppleTree object app.report();
report() method in AppleTree class will invoke and execute the statements written inside it.
in report() method, this statement System.out.println(\"apples: \" + apples); will print apples; 70. Becuase it uses global variable apple that is modified by grow() method.
So finally it will print
grow sees: 70
drop sees: 11
apples: 70
![Could you please explain why is this output: class TestApplesC { public static void main (String [] args) { AppleTree app = new AppleTree(); app.grow(); app.dro Could you please explain why is this output: class TestApplesC { public static void main (String [] args) { AppleTree app = new AppleTree(); app.grow(); app.dro](/WebImages/16/could-you-please-explain-why-is-this-output-class-testapples-1029275-1761533242-0.webp)
![Could you please explain why is this output: class TestApplesC { public static void main (String [] args) { AppleTree app = new AppleTree(); app.grow(); app.dro Could you please explain why is this output: class TestApplesC { public static void main (String [] args) { AppleTree app = new AppleTree(); app.grow(); app.dro](/WebImages/16/could-you-please-explain-why-is-this-output-class-testapples-1029275-1761533242-1.webp)