Search code examples
javastaticfieldabstract-classprivate

private field vs private static field in abstract class


I am confused about the scope of a private field versus a private static field of an abstract class. For example, consider the following classes and note the field validator,

abstract class ValidComponent {
    private static Validator validator = ... //(statement to instantiate new Validator)

    /** 
     *  This method is to be used by subclasses in their factory-methods 
     *  to do some validation logic after instantiation.
     */
    protected void selfValidate() {
        //validation logic
        ...
        validator.validate(this); // <<< This line uses the validator
        ...
    }
}

class ValidUsername extends ValidComponent {

    private @NotEmpty String core;
    private ValidUsername(String unamestr) {
        this.core = unamestr;
    }

    /** This is the factory-method who use selfValidate() */
    public static ValidUsername create(String unamestr) {
        ValidUsername vuname = new ValidUsername(unamestr);
        vuname.selfValidate();
        return vuname;
    }
}

class ValidEmail extends ValidComponent {
    private @Email String core;
    private ValidEmail(String emailstr) {
        this.core = emailstr;
    }

    /** This is the factory-method who use selfValidate() */
    public static ValidEmail create(String emailstr) {
        ValidEmail vemail = new ValidEmail(emailstr);
        vemail.selfValidate();
        return vemail;
    }
}

The abstract class ValidComponent prepares method selfValidate(), in which the private static field, validator, is used.

The ValidUsername and ValidEmail are subclasses that illustrate the intention of their base class: the method selfValidate() are used in their factory-methods to validate themself.

If my understanding is correct, when vuname.selfValidate() and vemail.selfValidate() are called, both use the same Validator object, i.e. ValidComponent.validator.

But what if I happen to change the modifiers of validator from private static to only private, are Validor objects used in vuname.selfValidate() and vemail.selfValidate() still the same object?


Solution

  • Consider a private variable,

    private String name;
    

    and its getter/setter which are ofcourse public.

    Now every class has access to getter/setter which in its implementation uses private variable. That's the purpose of private variables, not accessing it directly from other classes.

    Your case is similar where in private validator is being accessed by selfValidate() method. By their signature, selfValidate() is accessible to subclasses.

    To answer your question about whether validator object will be different in case of non-static or not, then every class that accesses it will create a new instance of that object.