Why we should not use protected static in java

java protected static method
protected static c#
static java
protected static php
protected java
static modifiers in java
protected static c++
public, private static protected java

I was going through this question Is there a way to override class variables in Java? The first comment with 36 upvotes was:

If you ever see a protected static, run.

Can anyone explain why is a protected static frowned upon?

It's more a stylistic thing than a direct problem. It suggests that you haven't properly thought through what is going on with the class.

Think about what static means:

This variable exists at class level, it does not exist separately for each instance and it does not have an independent existence in classes which extend me.

Think about what protected means:

This variable can be seen by this class, classes in the same package and classes which extend me.

The two meanings are not exactly mutually exclusive but it is pretty close.

The only case I can see where you might use the two together is if you had an abstract class that was designed to be extended and the extending class could then modify the behavior using constants defined in the original. That sort of arrangement would most likely end up very messy though and indicates weakness in the design of the classes.

In most cases it would be better to have the constants as public since that just makes everything cleaner and allows the people sub-classing more flexibility. Quite apart from anything else in many cases composition is preferable to inheritance, while abstract classes force inheritance.

To see one example of how this could break things and to illustrate what I mean by the variable not having an independent existence try this example code:

public class Program {
    public static void main (String[] args) throws java.lang.Exception {
        System.out.println(new Test2().getTest());
        Test.test = "changed";
        System.out.println(new Test2().getTest());
    }
}

abstract class Test {
    protected static String test = "test";
}

class Test2 extends Test {
    public String getTest() {
        return test;
    }
}

You will see the results:

test
changed

Try it yourself at: https://ideone.com/KM8u8O

The class Test2 is able to access the static member test from Test without needing to qualify the name - but it does not inherit or get its own copy. It is looking at the exact same object in memory.

oop - Why we should not use protected static in java, It's more a stylistic thing than a direct problem. It suggests that you haven't properly thought through what is going on with the class. Think about  In a previous blog, I talked about why we cannot define an outer class using private or protected keywords.If you have not read it, please go ahead and give it a look. I this article, I will talk

It's frowned upon because it's contradictive.

Making a variable protected implies it will be used within the package or it will be inherited within a subclass.

Making the variable static makes it a member of the class, eliminating the intentions of inheriting it. This leaves only the intention of being used within a package, and we have package-private for that (no modifier).

The only situation I could find this useful for is if you were declaring a class that should be used to launch the application (like JavaFX's Application#launch, and only wanted to be able to launch from a subclass. If doing so, ensure the method is also final to disallow hiding. But this is not "the norm", and was probably implemented to prevent adding more complexity by adding a new way to launch applications.

To see the access levels of each modifier, see this: The Java Tutorials - Controlling Access to Members of a Class

what is difference between protected static method and protected , A static method is a method which doesn't belong to a particular instance of a class. It belongs to the class itself. You could write Demo2.demo() to call the static​  But there is one more reason for not using static variables and methods. Static methods and variables encourage procedural code to be written instead of object oriented. Now, it seems like we are failing at automation. It is not too bad to just have a static driver variable. But using static in other ways is not recommended.

Java static: 10 things you need to know about the static modifier, As a result, you can use the class's name to call a static method or reference And protected fields are available to all classes within a package, Unlike local variables, static fields and methods are NOT thread safe in Java. Because a static method is not (necessarily) bound to a specific instance of a class, it can only access static variables (the value of static variables is shared between all instances of a class while the value of a non-static variable is different for each instance you create with the new keyword).

Static members are not inherited, and protected members are only visible to subclasses (and of course the containing class), so a protected static has the same visibility as static, suggesting a misunderstanding by the coder.

What does 'static', 'instantiated', 'public', 'private' and 'protected , Static: The variable is common to the entire class, not specific to any object. public: Provides Can we use "static" to modify the constructor in Java, and why​? Mind you, a static nested class in C# isn't the same as a static nested class in Java :) – Jon Skeet Oct 31 '08 at 17:13 2 Nested types are one of those areas where C# got it extremely correct compared to Java.

Actually there is nothing fundamentally wrong with protected static. If you really want a static variable or method that is visible for the package and all subclasses of the declaring class then go ahead and make it protected static.

Some people generally avoid to use protected for various reasons and some people think non-final static variables should be avoided by all means (I personally sympathize with the latter to some degree), so I guess the combination of protected and static must look bad^2 to those that belong to both groups.

protected static method visibility (OCPJP forum at Coderanch), Hello from Java Junior Subclass using reference on superclass can "see" protected static method but cannot see non static protected If Croatia was not a country you will get protected access error when trying to do either. Variable is static because it is going to be used by a getter and the getter is static. (If the getter is not static then the getter will instantiate the class every time it is called, it violates Singleton’s principle.) It is private because you don’t want any other class to have a direct access over it.

Java Access Modifiers, Java Access Modifiers - Public, Private, Protected & Default: Access Modifiers is When we do not mention any access modifier, it is called default access modifier. get error because the * class we are trying to use has default access * modifier. public class Test { public static void main(String args[]){ Addition obj = new  Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.

Day 15 -- Modifiers, Access Control, and Class Design, In Week 1 you learned how to define classes, methods, and variables in Java. to a class, method, or variable: public, protected, and private; The static modifier for You may not think you've been using packages at all up to this point, but  static is a non-access modifier in Java which is applicable for the following: To create a static member (block,variable,method,nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

Java Access for control, private, public, and protected, Public access in Java is like hanging a sign that we are open for business. Although the public is easily accessible it is not recommended to use often. The static modifier gives us access to a method, block, variable, or nested class without  internal methods -> protected/private (no default because the extended classes, out the package, don't inheritance the methods) If I set a class as default, only classes in the same package can use it, hence I can use the default safely (public or protected are not useful here): DEFAULT CLASS: constructor -> default getter/setter -> default

Comments
  • There's nothing wrong with a protected static field, as long as it's final. A mutable static field shared across classes is definitely cause for worry. Multiple classes updating a static field is not likely to be reliable or easy to follow, especially since the presence of any protected field or method implies that the class is meant to be extended by classes in other packages, possibly classes not under the control of the author of the class containing the protected field.
  • @VGR, final doesn't means the field is immutable. You can always modify the object referenced by a final reference variable.
  • @VGR I disagree. The ONLY reason you would make a static variable is to have access to it from within another package only by inherience, and access to a single field should NOT be the reason for inheritence. It's a flawed design, IMO, and if you resort to that, you should probably rethink your application's structure. That's just my opinion though.
  • @LoneRider You're right. I was thinking immutable, and final certainly doesn't guarantee that.
  • Even I came here from the same question.
  • You guys are hung up on inheritance. The typical case where this is seen is someone wanting package access without making it public (e.g. a unit test).
  • @spudone but unit tests are generally placed in the same package. To give them access you just use the default (package) access level. Protected gives access to subclasses too which is not required or relevant to unit test.
  • @Kamafeather Protected means that children can see you from different classes and any classes in the same package can see you. So yes Program is in the same package and hence can see the protected member.
  • "the extending class could then modify the behavior" This would violate the Liskov Subsitution principle. A subclass should not modify the behavior of it's supertype. This falls under the whole "a square is not a rectangle" argument: adjusting the superclass (Rectangle) to adjust width/height to ensure equality will (for Square) will produce undesired results if you were to replace every supertype with an instance of it's subtype.
  • "The only case I can see where you might use the two together is if you had an abstract class that was designed to be extended and the extending class could then modify the behavior using constants defined in the original" A bit hidden, but it's in there. The code example also expresses the statement
  • I don't understand how would static eliminate the intentions of inheriting it. Because my subclass in another package still require the field of super to be protected to access, even though it's static. package-private cannot help
  • @AoboYang You're right, which is why some people use protected static. But it's a code smell, hence the "run" part. Access modifiers and inheritance are two different subjects. Yes, you won't be able to access a static member from a super class if it was package-private. But you shouldn't rely on inheritance to reference static fields in the first place; it's a sign of poor design. You'll notice attempts at overriding static methods give no results, which is a clear sign that inheritance is not class based. If you need access outside of the class or package, it should be public
  • I have a class with some private static util functions at first, but I think someone may want to improve or customize from my class and these util functions may also provide convenience to them. public may not be appropriate since util methods are not for the user of the instances of my class. Could you help me figure out a good design instead of protected? Thanks