简体   繁体   English

Java中私有静态变量的用途是什么?

[英]What is the use of a private static variable in Java?

If a variable is declared as public static varName;如果一个变量被声明为public static varName; , then I can access it from anywhere as ClassName.varName . ,然后我可以从任何地方访问它作为ClassName.varName I am also aware that static members are shared by all instances of a class and are not reallocated in each instance.我也知道静态成员由类的所有实例共享,并且不会在每个实例中重新分配。

Is declaring a variable as private static varName;将变量声明为private static varName; any different from declaring a variable private varName;与声明变量private varName;任何不同private varName; ? ?

In both cases it cannot be accessed as ClassName.varName or as ClassInstance.varName from any other class.在这两种情况下,它都不能作为ClassName.varName或作为ClassInstance.varName从任何其他类访问。

Does declaring the variable as static give it other special properties?将变量声明为静态是否会给它其他特殊属性?

Of course it can be accessed as ClassName.var_name , but only from inside the class in which it is defined - that's because it is defined as private .当然,它可以作为ClassName.var_name访问,但只能从定义它的类内部访问 - 那是因为它被定义为private

public static or private static variables are often used for constants. public staticprivate static变量通常用于常量。 For example, many people don't like to "hard-code" constants in their code;例如,许多人不喜欢在他们的代码中“硬编码”常量; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable.他们喜欢使用有意义的名称创建一个public staticprivate static变量,并在他们的代码中使用它,这应该使代码更具可读性。 (You should also make such constants final ). (您还应该将此类常量设为final )。

For example:例如:

public class Example {
    private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
    private final static String JDBC_USERNAME = "username";
    private final static String JDBC_PASSWORD = "password";

    public static void main(String[] args) {
        Connection conn = DriverManager.getConnection(JDBC_URL,
                                         JDBC_USERNAME, JDBC_PASSWORD);

        // ...
    }
}

Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.将其设为public还是private取决于您是否希望变量在类外可见。

Static variables have a single value for all instances of a class.静态变量对于类的所有实例都有一个值。

If you were to make something like:如果你要做这样的事情:

public class Person
{
    private static int numberOfEyes;
    private String name;
}

and then you wanted to change your name, that is fine, my name stays the same.然后你想改名,没关系,我的名字保持不变。 If, however you wanted to change it so that you had 17 eyes then everyone in the world would also have 17 eyes.然而,如果你想改变它,让你有 17 只眼睛,那么世界上每个人也会有 17 只眼睛。

Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class.私有静态变量的用处与私有实例变量的用处相同:它们存储只能由同一类中的代码访问的状态。 The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.变量的可访问性(私有/公共/等)和实例/静态性质是完全正交的概念。

I would avoid thinking of static variables as being shared between "all instances" of the class - that suggests there has to be at least one instance for the state to be present.我会避免将静态变量视为在类的“所有实例”之间共享 - 这表明必须至少有一个实例才能存在状态。 No - a static variable is associated with the type itself instead of any instances of the type.否 - 静态变量与类型本身相关联,而不是与该类型的任何实例相关联。

So any time you want some state which is associated with the type rather than any particular instance, and you want to keep that state private (perhaps allowing controlled access via properties, for example) it makes sense to have a private static variable.因此,任何时候您想要某个与类型相关联的状态而不是任何特定实例,并且您希望保持该状态私有(例如,可能允许通过属性进行受控访问),拥有一个私有静态变量是有意义的。

As an aside, I would strongly recommend that the only type of variables which you make public (or even non-private) are constants - static final variables of immutable types.顺便说一句,我强烈建议您公开(甚至非私有)的唯一变量类型是常量 - 不可变类型的静态最终变量。 Everything else should be private for the sake of separating API and implementation (amongst other things).为了分离 API 和实现(除其他外),其他一切都应该是私有的。

Well you are right public static variables are used without making an instance of the class but private static variables are not.好吧,您是对的,公共静态变量在不创建类的实例的情况下使用,但私有静态变量不是。 The main difference between them and where I use the private static variables is when you need to use a variable in a static function.它们与我使用私有静态变量的主要区别在于何时需要在静态函数中使用变量。 For the static functions you can only use static variables, so you make them private to not access them from other classes.对于静态函数,您只能使用静态变量,因此您将它们设为私有以防止从其他类访问它们。 That is the only case I use private static for.这是我使用私有静态的唯一情况。

Here is an example:下面是一个例子:

Class test {
   public static String name = "AA";
   private static String age;

   public static void setAge(String yourAge) {
       //here if the age variable is not static you will get an error that you cannot access non static variables from static procedures so you have to make it static and private to not be accessed from other classes
       age = yourAge;
   }
}

Well, private static variables can be used to share data across instances of that class.好吧, private static变量可用于在该类的实例之间共享数据。 While you are correct that we cannot access the private static variables using constructs like ClassName.member or ClassInstance.member but the member will always be visible from methods of that class or instances of that class.虽然您是正确的,我们无法使用ClassName.memberClassInstance.member类的构造访问private static变量,但该成员将始终从该类的方法或该类的实例中可见。 So in effect instances of that class will always be able to refer to member.因此,实际上该类的实例将始终能够引用成员。

Is declaring a variable as private static varName;将变量声明为private static varName; any different from declaring a variable private varName;与声明变量private varName;任何不同private varName; ? ?

Yes, both are different.是的,两者是不同的。 And the first one is called class variable because it holds single value for that class whereas the other one is called instance variable because it can hold different value for different instances(Objects) .和第一个被调用class variable ,因为它适用于该单值class而另一个被称为instance variable ,因为它可以保持不同的不同的值instances(Objects) The first one is created only once in jvm and other one is created once per instance ie if you have 10 instances then you will have 10 different private varName;第一个在 jvm 中只创建一次,另一个每个实例创建一次,即如果你有 10 个实例,那么你将有 10 个不同的private varName; in jvm.在 jvm 中。

Does declaring the variable as static give it other special properties?将变量声明为static是否会给它其他特殊属性?

Yes, static variables gets some different properties than normal instance variables.是的,静态变量与普通实例变量有一些不同的属性。 I've mentioned few already and let's see some here: class variables (instance variables which are declared as static) can be accessed directly by using class name like ClassName.varName .我已经提到了一些,让我们在这里看看: class variables (声明为静态的实例变量)可以通过使用类名直接访问,如ClassName.varName And any object of that class can access and modify its value unlike instance variables are accessed by only its respective objects.并且该类的任何对象都可以访问和修改其值,而实例变量只能由其各自的对象访问。 Class variables can be used in static methods.类变量可以在静态方法中使用。

What is the use of a private static variable in Java? Java中private static variable的用途是什么?

Logically, private static variable is no different from public static variable rather the first one gives you more control.从逻辑上讲, private static variablepublic static variable没有什么不同,第一个给你更多的控制权。 IMO, you can literally replace public static variable by private static variable with help of public static getter and setter methods. IMO,您可以在public static getter 和 setter 方法的帮助下用private static variable替换public static variable

One widely used area of private static variable is in implementation of simple Singleton pattern where you will have only single instance of that class in whole world. private static variable一个广泛使用的领域是实现简单的Singleton模式,在这种模式下,全世界只有该类的单个实例。 Here static identifier plays crucial role to make that single instance is accessible by outside world(Of course public static getter method also plays main role).这里static标识符起着至关重要的作用,使外部世界可以访问单个实例(当然公共静态 getter 方法也起着主要作用)。

public class Singleton {
    private static Singleton singletonInstance = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return Singleton.singletonInstance;
    }
}

What is the use of a private static class variable?私有静态类变量有什么用?

Let's say you have a library book Class.假设您有一个图书馆书籍类。 Each time you create a new Book, you want to assign it a unique id.每次创建新 Book 时,您都希望为其分配一个唯一的 id。 One way is to simply start at 0 and increment the id number.一种方法是简单地从 0 开始并递增 id 号。 But, how do all the other books know the last created id number?但是,所有其他书籍如何知道最后创建的 ID 号? Simple, save it as a static variable.很简单,把它保存为一个静态变量。 Do patrons need to know that the actual internal id number is for each book?读者是否需要知道每本书的实际内部 ID 号? No. That information is private.不,该信息是私密的。

public class Book {
    private static int numBooks = 0;
    private int id;
    public String name;

    Book(String name) {
        id = numBooks++;
        this.name = name;
    }
}

This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else.这是一个人为的例子,但我相信您很容易想到这样的情况,您希望所有类实例都可以访问应该对其他人保密的公共信息。 Or even if you can't, it is good programming practice to make things as private as possible.或者,即使您不能,将事情尽可能保密也是一种很好的编程习惯。 What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it.如果您不小心将 numBooks 字段设为公开,即使 Book 用户不应该对它做任何事情,该怎么办。 Then someone could change the number of Books without creating a new Book.然后有人可以在不创建新书的情况下更改书的数量。

Very sneaky!非常狡猾!

The private keyword will allow the use for the variable access within the class and static means we can access the variable in a static method. private关键字将允许在类中使用变量访问,而static意味着我们可以在静态方法中访问变量。

You may need this cause a non-static reference variable cannot be accessible in a static method.您可能需要这样做,因为在静态方法中无法访问非静态引用变量。

Another perspective :另一个观点:

  1. A class and its instance are two different things at the runtime.一个类和它的实例在运行时是两个不同的东西。 A class info is "shared" by all the instances of that class.类信息由该类的所有实例“共享”。
  2. The non-static class variables belong to instances and the static variable belongs to class.非静态类变量属于实例,静态变量属于类。
  3. Just like an instance variables can be private or public, static variables can also be private or public.就像实例变量可以是私有的或公共的一样,静态变量也可以是私有的或公共的。

静态变量是那些对类的所有实例通用的变量..如果一个实例更改了它..那么静态变量的值将为所有其他实例更新

For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers.对于某些人来说,如果他们在几种不同的语言中看到它会更有意义,所以我在我的页面上用 Java 和 PHP 编写了一个示例,其中我解释了其中的一些修饰符。 You might be thinking about this incorrectly.您可能会错误地考虑这一点。

You should look at my examples if it doesn't make sense below.如果下面没有意义,你应该看看我的例子。 Go here http://www.siteconsortium.com/h/D0000D.php去这里http://www.siteconsortium.com/h/D0000D.php

The bottom line though is that it is pretty much exactly what it says it is.但最重要的是,它几乎就是它所说的那样。 It's a static member variable that is private.它是一个私有的静态成员变量。 For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public.例如,如果您想创建一个 Singleton 对象,为什么要公开 SingletonExample.instance 变量。 If you did a person who was using the class could easily overwrite the value.如果您这样做,使用该类的人很容易覆盖该值。

That's all it is.这就是全部。

public class SingletonExample {
      private static SingletonExample instance = null;
      private static int value = 0;
      private SingletonExample() {
        ++this.value;
      }
      public static SingletonExample getInstance() {
        if(instance!=null)
        return instance;
        synchronized(SingletonExample.class) {
        instance = new SingletonExample();
        return instance;
        }
      }
      public void printValue() {
        System.out.print( this.value );
      }

      public static void main(String [] args) {
        SingletonExample instance = getInstance();
        instance.printValue();
        instance = getInstance();
        instance.printValue();
         }
    }

If you use private static variables in your class, Static Inner classes in your class can reach your variables.如果您在类中使用私有静态变量,则类中的静态内部类可以访问您的变量。 This is perfectly good for context security.这对上下文安全非常有用。

When in a static method you use a variable, the variable have to be static too as an example:在静态方法中使用变量时,变量也必须是静态的,例如:

private static int a=0;  
public static void testMethod() {  
        a=1;  
}

If a variable is defined as public static it can be accessed via its class name from any class.如果一个变量被定义为 public static 它可以通过它的类名从任何类访问。

Usually functions are defined as public static which can be accessed just by calling the implementing class name.通常函数被定义为公共静态,只需调用实现类名即可访问。

A very good example of it is the sleep() method in Thread class一个很好的例子是 Thread 类中的sleep()方法

Thread.sleep(2500);

If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you).如果变量定义为私有静态变量,则只能在该类中访问它,因此不需要类名,或者您仍然可以使用类名(由您决定)。 The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)私有变量名和私有静态变量名的区别在于私有静态变量只能被类的静态方法访问,而私有变量可以被该类的任何方法访问(静态方法除外)

A very good example of it is while defining database connections or constants which require declaring variable as private static .一个很好的例子是在定义需要将变量声明为 private static 的数据库连接或常量时。

Another common example is另一个常见的例子是

private static int numberOfCars=10;

public static int returnNumber(){

return numberOfCars;

}

I'm new to Java, but one way I use static variables, as I'm assuming many people do, is to count the number of instances of the class.我是 Java 新手,但是我使用静态变量的一种方法,正如我假设很多人所做的那样,是计算类的实例数。 eg:例如:

public Class Company {
    private static int numCompanies;

    public static int getNumCompanies(){
        return numCompanies;
    }
}

Then you can sysout:然后你可以系统输出:

Company.getNumCompanies();

You can also get access to numCompanies from each instance of the class (which I don't completely understand), but it won't be in a "static way".您还可以从类的每个实例(我不完全理解)访问 numCompanies,但它不会以“静态方式”进行。 I have no idea if this is best practice or not, but it makes sense to me.我不知道这是否是最佳实践,但对我来说很有意义。

*)If a variable is declared as private then it is not visible outside of the class.this is called as datahiding. *)如果一个变量被声明为私有,那么它在类之外是不可见的。这被称为数据隐藏。

*)If a variable is declared as static then the value of the variable is same for all the instances and we no need to create an object to call that variable.we can call that variable by simply *)如果一个变量被声明为静态,那么变量的值对于所有实例都是相同的,我们不需要创建一个对象来调用该变量。我们可以简单地调用该变量

classname.variablename;类名。变量名;

private static variable will be shared in subclass as well.私有静态变量也将在子类中共享。 If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.如果您在一个子类中进行了更改,而另一个子类将获得更改后的值,在这种情况下,它可能不是您所期望的。

public class PrivateStatic {

private static int var = 10;
public void setVar(int newVal) {
    var = newVal;
}

public int getVar() {
    return var;
}

public static void main(String... args) {
    PrivateStatic p1 = new Sub1();
    System.out.println(PrivateStatic.var);
    p1.setVar(200);

    PrivateStatic p2 = new Sub2();
    System.out.println(p2.getVar());
}
}


class Sub1 extends PrivateStatic {

}

class Sub2 extends PrivateStatic {
}

ThreadLocal variables are typically implemented as private static . ThreadLocal变量通常实现为private static In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.这样,它们就不会绑定到类,并且每个线程都有对自己的“ThreadLocal”对象的引用。

In the following example, eye is changed by PersonB, while leg stays the same.在以下示例中, eye是由PersonB变化,而leg保持不变。 This is because a private variable makes a copy of itself to the method, so that its original value stays the same;这是因为私有变量将自身复制到方法中,因此其原始值保持不变; while a private static value only has one copy for all the methods to share, so editing its value will change its original value.而私有静态值只有一个副本供所有方法共享,因此编辑其值将更改其原始值。

public class test {
private static int eye=2;
private int leg=3;

public test (int eyes, int legs){
    eye = eyes;
    leg=leg;
}

public test (){
}

public void print(){
    System.out.println(eye);
    System.out.println(leg);
}

public static void main(String[] args){
    test PersonA = new test();      
    test PersonB = new test(14,8);
    PersonA.print();    
}

} }

> 14 3 > 14 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM