IT

정적과 최종의 차이점은 무엇입니까?

lottoking 2020. 6. 1. 08:12
반응형

정적과 최종의 차이점은 무엇입니까?


나는 항상 javastaticfinal키워드를 혼동 합니다.

그들은 어떻게 다릅니 까?


정적 키워드는 4 가지 시나리오에서 사용될 수 있습니다.

  • 정적 변수
  • 정적 메소드
  • 정적 코드 블록
  • 정적 중첩 클래스

정적 변수와 정적 메소드를 먼저 살펴 보자.

정적 변수

  • 클래스에 속하고 객체 (인스턴스)가 아닌 변수입니다.
  • 정적 변수는 실행 시작시 한 번만 초기화됩니다. 이러한 변수는 인스턴스 변수를 초기화하기 전에 먼저 초기화됩니다.
  • 클래스의 모든 인스턴스가 공유 할 단일 사본입니다.
  • 정적 변수는 클래스 이름으로 직접 액세스 할 수 있으며 객체가 필요하지 않습니다.
  • 통사론: Class.variable

정적 방법

  • 객체 (인스턴스)가 아닌 클래스에 속하는 메소드입니다.
  • 정적 메소드는 정적 데이터에만 액세스 할 수 있습니다. 비 정적 데이터 (인스턴스 변수)는 클래스의 인스턴스를 가지고 있거나 작성하지 않는 한 액세스 할 수 없습니다.
  • 정적 메서드는 다른 정적 메서드 만 호출 할 수 있으며 클래스의 인스턴스를 만들거나 만들지 않는 한 정적이 아닌 메서드를 호출 할 수 없습니다.
  • 정적 메소드는 클래스 이름으로 직접 액세스 할 수 있으며 객체가 필요하지 않습니다.
  • 통사론: Class.methodName()
  • 정적 방법을 참조 할 수 없습니다 this또는 super어쨌든 키워드.

정적 클래스

Java에는 "정적 중첩 클래스"도 있습니다. 정적 중첩 클래스는 암시 적으로 외부 클래스의 인스턴스에 대한 참조가없는 클래스입니다.

정적 중첩 클래스는 인스턴스 메소드와 정적 메소드를 가질 수 있습니다.

Java에는 최상위 정적 클래스와 같은 것이 없습니다.

사이드 노트 :

주요 방법은 static인스턴스화가 발생하기 전에 응용 프로그램을 실행하기 위해 액세스 할 수 있어야하기 때문입니다.

final 키워드는 여러 컨텍스트에서 사용되어 나중에 변경할 수없는 엔티티를 정의합니다.

  • final클래스는 서브 클래스화할 수 없습니다. 이는 보안 및 효율성의 이유로 수행됩니다. 따라서 많은 Java 표준 라이브러리 클래스는 final예를 들어 java.lang.Systemjava.lang.String입니다. final클래스의 모든 메소드 는 암시 적으로 final있습니다.

  • final방법은 서브 클래스에 의해 오버라이드 (override) 할 수 없습니다. 서브 클래스에서 예기치 않은 동작이 클래스의 기능이나 일관성에 중요한 메소드를 변경하는 것을 방지하는 데 사용됩니다.

  • final변수 만 초기화 또는 할당 문을 통해 중, 한 번 초기화 할 수 있습니다. 선언 시점에서 초기화 할 필요는 없습니다. 이것을 blank final변수 라고 합니다. 클래스의 빈 최종 인스턴스 변수는 클래스가 선언 된 클래스의 모든 생성자 끝에 반드시 지정되어야합니다. 마찬가지로 빈 최종 정적 변수는 선언 된 클래스의 정적 초기화 프로그램에 반드시 지정되어야합니다. 그렇지 않으면 두 경우 모두 컴파일 타임 오류가 발생합니다.

참고 : 변수가 참조 인 경우 다른 개체를 참조하기 위해 변수를 리 바인드 할 수 없습니다. 그러나 원래 변경 가능한 경우 참조하는 객체는 여전히 변경 가능합니다.

익명의 내부 클래스가 메소드 본문 내에 정의되면 final해당 메소드의 범위에서 선언 모든 변수는 내부 클래스 내에서 액세스 할 수 있습니다. 일단 지정되면 최종 변수의 값을 변경할 수 없습니다.


static 은 인스턴스가 아닌 클래스에 속한다는 것을 의미합니다. 즉, 특정 Class 의 모든 인스턴스간에 공유되는 해당 변수 / 메소드의 사본이 하나만 있음을 의미합니다 .

public class MyClass {
    public static int myVariable = 0; 
}

//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();

MyClass.myVariable = 5;  //This change is reflected in both instances

final 은 전적으로 관련이 없으며 한 번만 초기화를 정의하는 방법입니다. 변수를 정의 할 때 또는 생성자 내에서 다른 곳에서 초기화 할 수 있습니다.

note 최종 메서드 및 최종 클래스에 대한 참고 사항으로, 메서드 또는 클래스를 각각 재정의 / 확장 할 수 없음을 명시 적으로 나타내는 방법입니다.

추가 읽기 정적 주제에 대해서는 정적 블록에서 사용되는 다른 용도에 대해 이야기했습니다. 정적 변수를 사용할 때 클래스를 사용하기 전에 이러한 변수를 설정해야하는 경우도 있지만 불행히도 생성자를 얻지 못합니다. 정적 키워드가 나오는 곳입니다.

public class MyClass {

    public static List<String> cars = new ArrayList<String>();

    static {
        cars.add("Ferrari");
        cars.add("Scoda");
    }

}

public class TestClass {

    public static void main(String args[]) {
        System.out.println(MyClass.cars.get(0));  //This will print Ferrari
    }
}

인스턴스 생성자 전에 호출되는 인스턴스 초기화 블록과 혼동해서는 안됩니다 .


이 둘은 실제로 비슷하지 않습니다. static필드는 클래스의 특정 인스턴스에 속하지 않는 필드입니다 .

class C {
    public static int n = 42;
}

Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.

final on the other hand indicates that a particular variable cannot change after it is initialized.

class C {
    public final int n = 42;
}

Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.

Also, classes can be declared final which indicates that they cannot be extended:

final class C {}

class B extends C {}  // error!

Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:

class C {
    public final void foo() {}
}

class B extends C {
    public void foo() {}  // error!
}

final -

1)When we apply "final" keyword to a variable,the value of that variable remains constant. (or) Once we declare a variable as final.the value of that variable cannot be changed.

2)It is useful when a variable value does not change during the life time of a program

static -

1)when we apply "static" keyword to a variable ,it means it belongs to class.
2)When we apply "static" keyword to a method,it means the method can be accessed without creating any instance of the class


static means there is only one copy of the variable in memory shared by all instances of the class.

The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.


Static and final have some big differences:

Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:

public class Test{    
   public final int first = 10;
   public static int second = 20;

   public Test(){
     second = second + 1
     first = first + 1;
   }
}

The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.


Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

Declaring

static final String color = "Black"; 

will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.

public class Speaker {

static String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //will provide output as "Black"
            Speaker.color = "white";
    System.out.println(Speaker.color);  //will provide output as "White"
}}

Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.

public class Speaker {

static final String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //should provide output as "Black"
            Speaker.color = "white"; //Error because the value of color is fixed.  
    System.out.println(Speaker.color); //Code won't execute.
}}

You may copy/paste this code directly into your emulator and try.


Static is something that any object in a class can call, that inherently belongs to an object type.

A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.

Some example code:

class someClass
{
   public static int count=0;
   public final String mName;

   someClass(String name)
   {
     mname=name;
     count=count+1;
   }

  public static void main(String args[])
  {
    someClass obj1=new someClass("obj1");
    System.out.println("count="+count+" name="+obj1.mName);
    someClass obj2=new someClass("obj2");
    System.out.println("count="+count+" name="+obj2.mName);
  }
}

Wikipedia contains the complete list of java keywords.


Easy Difference,

Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.

Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again. you can create object of class but that object will not have different x in them. if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.

Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.

"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so Class A has x =5, i can call and change it by A.x=6; "


I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.

static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.

final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.


Static variable values can get changed although one copy of the variable traverse through the application, whereas Final Variable values can be initialized once and cannot be changed throughout the application.

참고URL : https://stackoverflow.com/questions/13772827/difference-between-static-and-final

반응형