someone explain why x equals 0? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
26th Dec 2019, 9:36 AM
jcx2010
11 Answers
+ 1
If you do not remove it then it will be a local variable and it's scope will be limited to the constructor block. But if you remove int then the instance variable x which is declared outside the constructor will be modified.
26th Dec 2019, 10:25 AM
Avinesh
Avinesh - avatar
+ 2
Because x is an instance variable and they have default values, it is 0 for int type. Edit: To get 5 as output, kindly remove the "int" inside both constructors. c=5; & x=c;
26th Dec 2019, 9:40 AM
Avinesh
Avinesh - avatar
+ 1
Avinesh finally figured out the machinenics,pretty much helpful!
26th Dec 2019, 2:55 PM
jcx2010
0
Avinesh but the constructor of B got called,why x is still 0?
26th Dec 2019, 9:46 AM
jcx2010
0
Avinesh so the value of x didnt be accessed,thank you
26th Dec 2019, 9:52 AM
jcx2010
26th Dec 2019, 9:53 AM
Avinesh
Avinesh - avatar
0
Avinesh why int should be removed?thanks
26th Dec 2019, 10:06 AM
jcx2010
0
jcx2010 good to know that👍
26th Dec 2019, 3:02 PM
Avinesh
Avinesh - avatar
0
You are creating new local variable Just remove int from constructors
28th Dec 2019, 5:12 AM
Kaushal Kumar
Kaushal Kumar - avatar
0
Forgot "this" in constructor
25th Jan 2020, 7:11 PM
Артем Прохоров
Артем Прохоров - avatar
25th Jan 2020, 7:14 PM
Артем Прохоров
Артем Прохоров - avatar