1
class Parent
{
    static int y = 4;
}

class Child extends Parent
{
    static
    {
        System.out.print("static Initialization block ");
        y=9;
    }
    static void fun()
    {
        System.out.print(y);
    }
}

public class Test
{
    public static void main(String []args)
    {
        System.out.print(Child.y); // line L1
        Child.fun(); // line L2
    }
}

Line 1 outputs: 4

Line 2 Outputs: static Initialization block 9

Now, my Doubts are:

  1. I have read that whenever we initialize a class, static initialization block executed first then why line L1 not executing the static initialization block, while line L2 executes the static initialization block ?
  2. Does the static variable y of parent class inherited to child class or not?
1
  • 3
    Child.y is interpreted as Parent.y in this case, because y is actually on Parent. Decompile your class file with javap -v to verify this. That's actually why Child.y is an antipattern: you should always access static fields with the "correct" class. Commented Aug 11, 2021 at 9:23

1 Answer 1

2

Compiler turns Child.y into Parent.y

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.