Field xxx is never assigned to, and will always have its default value null

前端 未结 4 1275
南方客
南方客 2020-12-17 18:26

Anyone know whats this problem?

I got this warning Field xxx is never assigned to, and will always have its default value null on private sta

相关标签:
4条回答
  • 2020-12-17 19:10

    A static field is just a field whose value is shared by everyone. Think of it as a global variable. The thing is that you still need to instantiate it at least once. Usually, this is done at the same time/place than the declaration.

    public static Quantizer quantit = new Quantizer(?);
    

    I don't know much about what you want to do, but I don't think you really want to use a static field here. My guess is that you want to instantiate/create a new instance of Quantizer based on some input parameter (singlePass or doublePass). If the Quantizer class has no state, you should make it a singleton. If you want to do so, I suggest you look at Dependency Injection containers, like Castle Windsor, which can handle that for you more easily.

    0 讨论(0)
  • 2020-12-17 19:21

    Static members are accessed via the type name, i.e.

    Quantization.quantit = {some value};
    

    Of course since it is private you would have to so this from inside the type, in which case you can just use:

    quantit = {some value};
    

    However, I would also question whether static is an appropriate option here, especially if you are doing any threading (or web code). Static is often overused (and used inappropriately).

    0 讨论(0)
  • 2020-12-17 19:23

    The compiler is warning you that quantit is never initialized and will always be null.

    You probably should initialize it with an instance of a class that derives from ImageManipulation.Quantizer (you cannot instantiate Quantizer itself because it's an abstract class):

    private static Quantizer quantit = new QuantizerImplementation();
    
    0 讨论(0)
  • 2020-12-17 19:26

    You are never assigning an instance of the Quantizer class to your quantit static variable, so it will remain a null reference and will generate that exception when you'll try to use one of its methods. To fix the problem, just initialize that member with a new Quantizer object before using it.

    By the way, I'm not sure you want that variable to be static.

    Edit

    I saw just now that Quantizer is an abstract class... then you can't instantiate it directly, you have first to derive your specific class from it implementing the abstract methods (namely QuantizePixel and GetPalette) or use another ready-made class deriving from Quantizer, and then initialize the quantit field with a new instance of such class.

    0 讨论(0)
提交回复
热议问题