평신도 용어로 Java에서 '정적'이란 무엇을 의미합니까? [복제]
이 질문에 이미 답변이 있습니다.
- '정적'키워드는 클래스에서 무엇을합니까? 21 답변
나는 그것에 대한 몇 가지 정의를 들었고, Wikipedia에서 보았지만 Java 초보자로서 나는 그것이 의미하는 바를 여전히 확신하지 못합니다. 자바와 바보에 능통 한 사람?
static은 표시된 변수 또는 메서드를 클래스 수준에서 사용할 수 있음을 의미합니다. 즉, 액세스하기 위해 클래스의 인스턴스를 만들 필요가 없습니다.
public class Foo {
public static void doStuff(){
// does stuff
}
}
따라서 Foo의 인스턴스를 만든 다음 다음과 같이 호출하는 대신 doStuff
:
Foo f = new Foo();
f.doStuff();
다음과 같이 클래스에 대해 직접 메서드를 호출하면됩니다.
Foo.doStuff();
매우 평범한 용어로 클래스는 몰드이고 객체는 그 몰드로 만들어진 사본입니다. 정적은 금형에 속하며 복사하지 않고 직접 액세스 할 수 있으므로 위의 예
static 키워드는 Java에서 여러 가지 다른 방법으로 사용할 수 있으며 거의 모든 경우 수정 자입니다. 즉, 수정중인 것을 둘러싸는 객체 인스턴스없이 사용할 수 있습니다.
Java는 객체 지향 언어이며 기본적으로 작성하는 대부분의 코드에는 사용할 객체의 인스턴스가 필요합니다.
public class SomeObject {
public int someField;
public void someMethod() { };
public Class SomeInnerClass { };
}
someField, someMethod 또는 SomeInnerClass를 사용 하려면 먼저 SomeObject 인스턴스를 만들어야합니다 .
public class SomeOtherObject {
public void doSomeStuff() {
SomeObject anInstance = new SomeObject();
anInstance.someField = 7;
anInstance.someMethod();
//Non-static inner classes are usually not created outside of the
//class instance so you don't normally see this syntax
SomeInnerClass blah = anInstance.new SomeInnerClass();
}
}
이러한 것들을 정적으로 선언 하면 엔 클로징 인스턴스가 필요하지 않습니다 .
public class SomeObjectWithStaticStuff {
public static int someField;
public static void someMethod() { };
public static Class SomeInnerClass { };
}
public class SomeOtherObject {
public void doSomeStuff() {
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someMethod();
SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
//Or you can also do this if your imports are correct
SomeInnerClass blah2 = new SomeInnerClass();
}
}
정적 인 것을 선언하는 것은 몇 가지 의미를 갖습니다.
First, there can only ever one value of a static field throughout your entire application.
public class SomeOtherObject {
public void doSomeStuff() {
//Two objects, two different values
SomeObject instanceOne = new SomeObject();
SomeObject instanceTwo = new SomeObject();
instanceOne.someField = 7;
instanceTwo.someField = 10;
//Static object, only ever one value
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
}
}
The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).
public class SomeObjectWithStaticStuff {
private int nonStaticField;
private void nonStaticMethod() { };
public static void someStaticMethod() {
nonStaticField = 7; //Not allowed
this.nonStaticField = 7; //Not allowed, can never use *this* in static
nonStaticMethod(); //Not allowed
super.someSuperMethod(); //Not allowed, can never use *super* in static
}
public static class SomeStaticInnerClass {
public void doStuff() {
someStaticField = 7; //Not allowed
nonStaticMethod(); //Not allowed
someStaticMethod(); //This is ok
}
}
}
The static keyword can also be applied to inner interfaces, annotations, and enums.
public class SomeObject {
public static interface SomeInterface { };
public static @interface SomeAnnotation { };
public static enum SomeEnum { };
}
In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.
This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?
There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.
//SomeStaticThing.java
public class SomeStaticThing {
public static int StaticCounterOne = 0;
}
//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
public static int StaticCounterTwo = 0;
}
//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;
public class SomeOtherClass {
public void doStuff() {
StaticCounterOne++; //Ok
StaticCounterTwo++; //Not ok
SomeOtherStaticThing.StaticCounterTwo++; //Ok
}
}
Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.
public class SomeObject {
private static int x;
static {
x = 7;
}
}
Another great example of when static attributes and operations are used when you want to apply the Singleton design pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static
operation
In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.
Above points are correct and I want to add some more important points about Static keyword.
Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).
so you will get a doubt that what is the use of this right???
example: static int a=10;(1 program)
just now I told if you use static keyword for variables or for method it will store in permanent memory right.
so I declared same variable with keyword static in other program with different value.
example: static int a=20;(2 program)
the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.
In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.
overall i can say that,if we use static keyword
1.we can save memory
2.we can avoid duplicates
3.No need of creating object in-order to access static variable with the help of class name you can access it.
참고URL : https://stackoverflow.com/questions/2649213/in-laymans-terms-what-does-static-mean-in-java
'programing tip' 카테고리의 다른 글
Amazon Cognito 사용자 풀에서 클라이언트에 대한 비밀 해시를 확인할 수 없음 (0) | 2020.08.26 |
---|---|
웹 페이지에서 Apple의 새로운 San Francisco 글꼴을 사용하는 방법 (0) | 2020.08.26 |
XAMPP 아파치 서버 포트를 변경하는 방법은 무엇입니까? (0) | 2020.08.26 |
Java에서 더 이상 사용되지 않는 가져 오기 경고 표시 안 함 (0) | 2020.08.26 |
해결 실패 : com.android.support:cardview-v7:26.0.0 android (0) | 2020.08.26 |