+ 2
Find the output and give me the explanation please.
4 Réponses
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.
+ 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.
+ 1
thank you sir
0
i want more clearification...