0

I have an abstract class that is somewhat like a View from Android. I create a lot of classes that extend it to draw different stuff. Now i would like all those classes to share the same Paints so that colors match and so on.

My ideas would be

  • pass some context or windowmetrics to every single constructor, but that feels silly as i only need it once.

  • i could add a static method init() to the abstract class, but i try to avoid public static methods.

  • create a subclass with the single purpose to set the static members of the superclass and also null them at the end, something like a remote control to the superclass' static stuff.

im just not sure what risks there are or if there are even simpler ways to do it.

Edit: to init the static members i need a context (for those not familiar with android) and that context needs to be passed to that class, so no init in static blocks etc

NikkyD
  • 2,057
  • 1
  • 13
  • 29
  • Why do you need a static method in the abstract class for you purpose? In the constructor of the abstract class you can write the common logic to all the extending classes. Have a look at this answer http://stackoverflow.com/a/261159/572830 – Christian Achilli Nov 13 '12 at 10:37
  • I think you should look at defining your own custom Views or Styles, and then inherit from them – CocoNess Nov 13 '12 at 10:38
  • @TanjaV the problem remains, i have to pass some info at runtime to do final size calculations and that info i would like to share as static between all classes that inherit my base class – NikkyD Nov 14 '12 at 09:51
  • I dont really understand what youre trying to do. If you want to match colors, define the colors in an XML resource file – CocoNess Nov 14 '12 at 10:38
  • what i want to do is adapt textsizes at runtime to match the screen resolution, in XML you can only define DP or SP but no %-Pixels and weight cannot be applied to textsize. – NikkyD Nov 14 '12 at 10:56

2 Answers2

0

Or just add a static block and initialize them there:

public abstract class Foo {
    public static final int DEFAULT_PAINTS_SIZE = 5;
    public static Paint [] paints;

    static {
        paints = new Paints[DEFAULT_PAINTS_SIZE];
        // initialize the values somehow.
    }
}
duffymo
  • 293,097
  • 41
  • 348
  • 541
  • some settings are not available at startup so the static block would not have all the infos needed. – NikkyD Nov 15 '12 at 15:29
0

You can initialize them directly:

public class MyClass {
    private static MyStatic myStaticObject = new MyStatic();
}

or in a static initializer block:

public class MyClass {
    private static MyStatic myStaticObject;
    static {
        //something = stuff
        myStaticObject = new MyStatic(something);
        //more stuff
    }
}
Random42
  • 8,072
  • 6
  • 48
  • 79