+ 2

Find the output and give me the explanation please.

https://code.sololearn.com/cwEwNJJvZNqz/?ref=app

13th Oct 2017, 4:26 PM
Gajendra chouriya
Gajendra chouriya - avatar
4 Respostas
0
Compressing your code, changing "y" to "ya" & "yb", and adding a constructor for Program1 yields: public class Program{int a=4; public Program(){myMethod();} void myMethod(){a++;System .out.println("ya"+a);}} public class Program1 extends Program{int b=3; Program1(){System.out.println("b"+b);} void myMethod(){System .out.println("yb"+b);}} public class ProgramApp{ public static void main(String[] args){ Program1 p=new Program1();}} This generates output of: yb0 b3 so we know Program1's myMethod is run before Program1's constructor and b is 0 during myMethod and 3 in constructor. Therefore, assignment of 3 to b must be done in between them. Think of the constructor being coded as: Program1(){Program();b=3;System.out.println("b"+b);} Allocate storage for class, initialize static data & methods, initialize our parent class by calling it's constructor, initialize our classes data, call our constructor code. If you declared b static, you would get "y3" as you expected.
15th Oct 2017, 10:24 AM
John Wells
John Wells - avatar
+ 1
I believe what is happening is Program1's b hasn't been set as yet because it's constructor hasn't finished executing. You are calling it's myMethod to output b, but Program's constructor runs before Program1's.
13th Oct 2017, 4:52 PM
John Wells
John Wells - avatar
+ 1
thank you sir
15th Oct 2017, 10:57 AM
Gajendra chouriya
Gajendra chouriya - avatar
0
i want more clearification...
15th Oct 2017, 9:37 AM
Gajendra chouriya
Gajendra chouriya - avatar