+ 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); } }

11th Jul 2021, 2:20 PM
Yahel
Yahel - avatar
3 Answers
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
11th Jul 2021, 5:54 PM
Jayakrishna šŸ‡®šŸ‡³
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..?
11th Jul 2021, 6:48 PM
Yahel
Yahel - avatar
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. "
14th Jul 2021, 5:18 PM
Jayakrishna šŸ‡®šŸ‡³