0

Thanks in advance for the help!

I have a few classes that need to all include the same static block, like:

public class Class1 {
    static {
        changeState();
    }

    ...
}

public class Class2 {
    static {
        changeState();
    }

    ...
}

I currently have an abstract class that only includes the mentioned static block, and the others classes all extend the abstract class like:

public abstract class WithChangeState {
    static {
        changeState();
    }
}

public class Class1 extends WithChangeState {    
    ...
}

public class Class2 extends WithChangeState {
    ...
}

This doesn't "feel" like the right pattern. Are there other more elegant or correct ways to accomplish this?

markw
  • 321
  • 1
  • 3
  • 14
  • 1
    Create a utility class with a static method in it and access it using Classname. Good example in Java API is https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html class. – Amit Feb 02 '17 at 00:24
  • You've done it. You wanted to inherit a static block, you're inheriting a static block. What's the problem with that? – user207421 Feb 02 '17 at 01:33

1 Answers1

0

Just for future reference, what I ended up doing was:

// utility class with a static method
public abstract class ChangeState {
    public static void initialize() {
        changeState();
    }
}

// access it using Classname
public class Class1 {    
    static {
        ChangeState.initialize();
    }
    ...
}

// access it using Classname
public class Class2 {
    static {
        ChangeState.initialize();
    }
    ...
}
markw
  • 321
  • 1
  • 3
  • 14
  • Hard to see the point of that. What improvement do you think it represents over what you had in your question? – user207421 Feb 02 '17 at 01:33
  • Which is the use case scenario you're trying to face with this solution? I mean, the `static` method `initialize` seems to me like a Constructor, isn't it? So, why don't you use basic OOP, instead of esoteric `static` methods? – riccardo.cardin Feb 02 '17 at 06:51
  • I want to install a security provider in multiple library classes. Some of which already extend abstract classes. I want access to security providers in the implementations. – markw Feb 02 '17 at 17:08