+ 2
How is the output 5 and not 6? (I'd like a walk through)
class parent{ static int y = 5; } class child extends parent{ static{ y=6; } } public class Program{ public static void main(String[] args){ System.out.println(child.y); } }
3 Respuestas
0
child.y refers to attribute of child class . if does not found then it refers from parent class. there it finding attribute y. but calling attributes does not create object or not execute class child.
So your static block in child class not executing..
if you do like :
new child();
System.out.println(child.y); returns 6
0
Jayakrishna🇮🇳 but aren't static blocks execute when loading into memory? Meaning it does the operation inside the block without a need to create an instance..?
0
Yahel
Static initializer-blocks aren't run until the class is initialized. See Java Language Specification(Static initializers)
A static initializer declared in a class is executed when the class is initialized. Together with any field initializers for class variables .
Your class child is never initialized; the reference to child.y is a reference to a field actually declared in class Super and does not trigger initialization of the class Sub.
" your example, A reference to a static field causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a sub class or an sub interface or a class that implements an interface. "