2

If we run derived class,it will print derived and parent..is there any way to prevent inheritance of static block ?

//Class 1

public class parent {
static {
      System.out.println("Parent");
}
}

//Class2

public class derived extends parent{
      static {
            System.out.println("derived");
      }

      public static void main(String [] args) {

      }
}

Basically I have some method in parent class which I want to inherit but dont want the processing which is happening in parent static block to happen when derived class is being instantiated. .Is there any way to do this or I will have to duplicate the code ?

6
  • 2
    "No" is the answer. Now, a question: why do you want to do that? Commented Jun 19, 2013 at 7:47
  • Seems like bad design. Would it be possible to refactor parent's static code into its constructor? Commented Jun 19, 2013 at 7:53
  • 1
    You really don't want static inintialisers doing anything other than setting up constants. Commented Jun 19, 2013 at 8:07
  • @fge well the code is legacy where in static intializers are used to configure loggers using DOMconfiguratgor.configure.Since it is one time activity,I cannot put this into constructor. Commented Jun 19, 2013 at 8:41
  • 1
    Yes you can: create a singleton! Commented Jun 19, 2013 at 8:42

2 Answers 2

10

NO. You cannot do that . Static initialzier blocks are not inherited . Static blocks are executed when class is loaded since your base class extends a super class , even the super class definition will be loaded by JVM when referring to your class.

As per the JLS 12.4.1:

When Initialization Occurs A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

• T is a class and an instance of T is created.

• T is a class and a static method declared by T is invoked.

• A static field declared by T is assigned.

• A static field declared by T is used and the field is not a constant variable (§4.12.4).

• T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

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

Comments

1

its not possible. Static block is executing during class loading and you can't prevent this without refactoring the parent class to not used the static block

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.