Programming

Java에서 개인 정적 변수를 사용하는 것은 무엇입니까?

procodes 2020. 6. 15. 22:15
반응형

Java에서 개인 정적 변수를 사용하는 것은 무엇입니까?


변수가로 선언되면 public static varName;어디서나 변수에 액세스 할 수 있습니다 ClassName.varName. 또한 정적 멤버는 클래스의 모든 인스턴스에서 공유되며 각 인스턴스에서 재 할당되지 않는다는 것을 알고 있습니다.

변수를 선언하는 것과 private static varName;다른 것으로 변수를 선언하고 private varName;있습니까?

두 경우 모두 다른 클래스 ClassName.varName또는 ClassInstance.varName다른 클래스에서 액세스 할 수 없습니다 .

변수를 정적으로 선언하면 다른 특수 속성이 제공됩니까?


물론로 액세스 할 수 ClassName.var_name있지만 정의 된 클래스 내부에서만 액세스 할 수 있습니다 private.

public static또는 private static변수는 종종 상수에 사용됩니다. 예를 들어, 많은 사람들이 자신의 코드에서 상수를 "하드 코딩"하는 것을 좋아하지 않습니다. 그들은 의미있는 이름으로 변수 public staticprivate static변수 를 만들고 그것을 코드에서 사용하기 때문에 코드를 더 읽기 쉽게 만들어야합니다. (또한 그러한 상수를 만들어야합니다 final).

예를 들면 다음과 같습니다.

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);

        // ...
    }
}

변수를 만들 public거나 private변수를 클래스 외부에 표시할지 여부에 따라 다릅니다.


정적 변수는 클래스의 모든 인스턴스에 대해 단일 값을 갖습니다.

다음과 같은 것을 만들어야한다면 :

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

이름을 바꾸고 싶었습니다. 제 이름은 그대로입니다. 그러나 만약 당신이 17 개의 눈을 갖도록 그것을 바꾸고 싶다면 세계의 모든 사람들이 17 개의 눈을 가질 것입니다.


프라이빗 정적 변수는 프라이빗 인스턴스 변수와 같은 방식으로 유용합니다. 동일한 클래스 내의 코드로만 액세스되는 상태를 저장합니다. 접근성 (private / public / etc)과 변수의 인스턴스 / 정적 특성은 전적으로 직교 개념입니다.

정적 변수가 클래스의 "모든 인스턴스"간에 공유되는 것으로 생각하지 않기를 원합니다. 즉 , 상태가 존재하려면 하나 이상의 인스턴스가 있어야 함을 나타냅니다. 아니오 - 정적 변수는 유형 자체 대신과 관련된 모든 유형의 인스턴스.

따라서 특정 인스턴스가 아닌 유형과 관련된 상태를 원할 때 언제든지 상태를 비공개로 유지하고 싶을 수도 있습니다 (예를 들어 속성을 통한 제어 된 액세스를 허용하는 경우) 전용 정적 변수를 갖는 것이 좋습니다.

따로, 공개 (또는 비공개) 변수를 만드는 유일한 변수 유형은 상수-불변 유형의 정적 최종 변수 인 것이 좋습니다. API와 구현을 분리하기 위해 다른 모든 것들은 비공개로해야합니다.


음, private static변수는 그 클래스의 인스턴스에서 데이터를 공유 할 수 있습니다. 당신은 우리가 액세스 할 수있는 올바른 동안 private static같은 구조를 사용하여 변수를 ClassName.member하거나 ClassInstance.member하지만, 회원은 항상 그 클래스의 클래스의 메소드 나 인스턴스에서 볼 수 있습니다. 따라서 실제로 해당 클래스의 인스턴스는 항상 멤버를 참조 할 수 있습니다.


글쎄 당신은 클래스의 인스턴스를 만들지 않고 공용 정적 변수를 사용하지만 개인 정적 변수는 그렇지 않습니다. 그들과 개인 정적 변수를 사용하는 위치의 주요 차이점은 정적 함수에서 변수를 사용해야 할 때입니다. 정적 함수의 경우 정적 변수 만 사용할 수 있으므로 다른 클래스에서 액세스하지 못하도록 비공개 변수로 설정하십시오. 그것이 개인 정적을 사용하는 유일한 경우입니다.

예를 들면 다음과 같습니다.

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;
   }
}

변수를 선언하는 것과 private static varName;다른 것으로 변수를 선언하고 private varName;있습니까?

예, 둘 다 다릅니다. 첫 번째 class variable값은 단일 값을 보유하기 때문에 호출 되는 class반면 instance variable다른 값은 다른 값을 보유 할 수 있기 때문에 호출 instances(Objects)됩니다. 첫 번째 인스턴스는 jvm에서 한 번만 작성되고 다른 인스턴스는 인스턴스 당 한 번 작성됩니다. 즉, 인스턴스가 10 개인 경우 private varName;jvm에서 10 개의 다른 항목이 작성 됩니다.

변수를 선언하면 static다른 특별한 속성이 부여됩니까?

예, 정적 변수는 일반 인스턴스 변수와 다른 속성을 갖습니다. 나는 이미 언급하지 않았고 여기에 몇 가지를 보자 : class variables(정적으로 선언 된 인스턴스 변수)는 같은 클래스 이름을 사용하여 직접 액세스 할 수 있습니다 ClassName.varName. 또한 인스턴스 변수가 해당 객체에서만 액세스되는 것과 달리 해당 클래스의 모든 객체는 해당 값에 액세스하고 값을 수정할 수 있습니다. 정적 변수에는 클래스 변수를 사용할 수 있습니다.

private static variableJava에서 무엇을 사용 합니까?

논리적으로, 첫 번째 private static variable와 다를 바없이 public static variable더 많은 것을 제어 할 수 있습니다. IMO, 당신은 말 그대로 대체 할 수있는 public static variableprivate static variable의 도움으로 public staticgetter와 setter 메소드.

널리 사용되는 영역 중 하나 는 전 세계에서 해당 클래스의 단일 인스턴스 만 갖는 private static variable간단한 Singleton패턴 을 구현하는 것입니다. 여기서 static식별자는 외부 세계에서 단일 인스턴스에 액세스 할 수 있도록하는 중요한 역할을합니다 (물론 공개 정적 게터 메소드도 주요 역할을 수행함).

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

    private Singleton(){}

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

개인 정적 클래스 변수의 사용은 무엇입니까?

도서관 서적 클래스가 있다고 가정 해 봅시다. 새 책을 만들 때마다 고유 한 ID를 할당하려고합니다. 한 가지 방법은 단순히 0에서 시작하여 id 번호를 늘리는 것입니다. 그러나 다른 모든 책은 마지막으로 생성 된 ID 번호를 어떻게 알 수 있습니까? 간단하게 정적 변수로 저장하십시오. 고객은 실제 내부 ID 번호가 각 책의 번호임을 알고 있어야합니까? 아닙니다. 그 정보는 비공개입니다.

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

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

이것은 고안된 예이지만 모든 클래스 인스턴스가 다른 사람으로부터 비공개로 유지해야하는 공통 정보에 액세스하려는 경우를 쉽게 생각할 수 있습니다. 또는 할 수없는 경우라도 가능한 한 사적인 것을 만드는 것이 좋은 프로그래밍 관행입니다. 책 사용자가 아무것도하지 않아도 numBooks 필드를 실수로 공개 한 경우 어떻게해야합니까? 그러면 누군가 새 책을 만들지 않고도 책 수를 변경할 수 있습니다.

매우 교활한!


private 키워드는 클래스 내 변수 액세스에 사용하고 정적 메소드에서 변수에 액세스 할 수 있다는 의미에서 정적을 유지하지만 참조 변수는 정적 메소드에서 액세스 할 수 없습니다.


다른 관점 :

  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.

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;  
}

Static variables are those variables which are common for all the instances of a class..if one instance changes it.. then value of static variable would be updated for all other instances


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. 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

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. 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.


If a variable is defined as public static it can be accessed via its class name from any class.

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(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 .

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. e.g.:

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". 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. On this way, they are not bound to the class and each thread has its own reference to its own "threadLocal" object.


In the following example, eye is changed by PersonB, while leg stays the same. 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

참고URL : https://stackoverflow.com/questions/7279887/what-is-the-use-of-a-private-static-variable-in-java

반응형