정적 방법과 비 정적 방법의 차이점은 무엇입니까?
아래 코드 조각을 참조하십시오.
코드 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
코드 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
이 코드 조각의 차이점은 무엇입니까? 둘 다 15대답으로 출력 됩니다.
정적 메서드는 클래스 자체에 속하고 비 정적 (일명 인스턴스) 메서드는 해당 클래스에서 생성 된 각 객체에 속합니다. 메서드가 클래스의 개별 특성에 의존하지 않는 작업을 수행하는 경우이를 정적으로 만드십시오 (프로그램의 풋 프린트가 작아짐). 그렇지 않으면 비 정적이어야합니다.
예:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
다음과 같은 정적 메서드를 호출 할 수 있습니다 Foo.method1().. method2로 시도하면 실패합니다. 그러나 이것은 작동합니다.Foo bar = new Foo(1); bar.method2();
정적 메서드는 메서드를 사용할 인스턴스 (상황, 상황)가 하나만 있고 여러 복사본 (객체)이 필요하지 않은 경우에 유용합니다. 예를 들어, 하나의 웹 사이트에만 로그온하고 날씨 데이터를 다운로드 한 다음 값을 반환하는 메서드를 작성하는 경우 메서드 내에서 필요한 모든 데이터를 하드 코딩 할 수 있기 때문에 정적으로 작성할 수 있습니다. 여러 인스턴스 나 복사본이 없을 것입니다. 그런 다음 다음 중 하나를 사용하여 메서드에 정적으로 액세스 할 수 있습니다.
MyClass.myMethod();
this.myMethod();
myMethod();
방법을 사용하여 여러 복사본을 만들려는 경우 비 정적 방법이 사용됩니다. 예를 들어 보스턴, 마이애미 및 로스 앤젤레스에서 날씨 데이터를 다운로드하고 각 개별 위치에 대한 코드를 개별적으로 사용자 지정할 필요없이 메서드 내에서 다운로드 할 수있는 경우 메서드에 비 정적으로 액세스합니다. :
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
위의 예에서 Java는 "boston", "miami"또는 "losAngeles"참조를 사용하여 개별적으로 액세스 할 수있는 동일한 메서드에서 세 개의 개별 개체와 메모리 위치를 만듭니다. MyClass.myMethod (); 때문에 위의 어떤 것도 정적으로 액세스 할 수 없습니다. 비 정적 참조가 만든 개별 객체가 아니라 메서드에 대한 일반 참조입니다.
각 위치에 액세스하는 방식이나 데이터가 반환되는 방식이 충분히 다른 상황에 처하여 많은 수고를 거치지 않고는 "하나의 크기에 모두 적용"방법을 작성할 수없는 경우 더 나을 수 있습니다. 각 위치에 하나씩 세 가지 별도의 정적 메서드를 작성하여 목표를 달성하십시오.
일반적으로
static : 직접 호출 할 수있는 객체를 만들 필요가 없습니다.
ClassName.methodname()
Non Static : 다음과 같은 객체를 생성해야합니다.
ClassName obj=new ClassName()
obj.methodname();
A static method belongs to the class and a non-static method belongs to an object of a class. That is, a non-static method can only be called on an object of a class that it belongs to. A static method can however be called both on the class as well as an object of the class. A static method can access only static members. A non-static method can access both static and non-static members because at the time when the static method is called, the class might not be instantiated (if it is called on the class itself). In the other case, a non-static method can only be called when the class has already been instantiated. A static method is shared by all instances of the class. These are some of the basic differences. I would also like to point out an often ignored difference in this context. Whenever a method is called in C++/Java/C#, an implicit argument (the 'this' reference) is passed along with/without the other parameters. In case of a static method call, the 'this' reference is not passed as static methods belong to a class and hence do not have the 'this' reference.
참조 : 정적 대 비 정적 방법
더 기술적으로 말하면 정적 메서드와 가상 메서드의 차이점은 연결 방식입니다.
대부분의 OO가 아닌 언어에서와 같은 전통적인 "정적"메서드는 컴파일 타임에 구현에 "정적으로"연결 / 연결됩니다. 즉, 프로그램 A에서 Y () 메서드를 호출하고 프로그램 A를 Y ()를 구현하는 라이브러리 X에 연결하면 XY ()의 주소가 A로 하드 코딩되므로 변경할 수 없습니다.
JAVA와 같은 OO 언어에서 "가상"메서드는 런타임에 "늦게"해결되며 클래스의 인스턴스를 제공해야합니다. 따라서 프로그램 A에서 가상 메서드 Y ()를 호출하려면 인스턴스, 예를 들어 BY ()를 제공해야합니다. 런타임에 A가 BY ()를 호출 할 때마다 호출 된 구현은 사용 된 인스턴스에 따라 달라 지므로 BY (), CY () 등은 모두 런타임에 Y ()의 다른 구현을 제공 할 수 있습니다.
왜 그게 필요할까요? 그렇게하면 종속성에서 코드를 분리 할 수 있기 때문입니다. 예를 들어, 프로그램 A가 "draw ()"를하고 있다고 가정합니다. 정적 언어를 사용하면 그게 다이지만 OO를 사용하면 B.draw ()를 수행하고 실제 그리기는 런타임에 원을 사각형으로 변경할 수있는 객체 B의 유형에 따라 달라집니다. 이렇게하면 코드가 코드 작성 후 새로운 유형의 B가 제공 되더라도 변경할 필요없이 여러 가지를 그립니다. 멋진-
정적 메서드는 클래스에 속하고 비 정적 메서드는 클래스의 객체에 속합니다. 출력 간의 차이를 만드는 방법에 대한 한 가지 예를 제공합니다.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
이제 출력은 다음과 같습니다. ::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
메서드가 객체의 특성과 관련된 경우 비 정적 메서드로 정의해야합니다. 그렇지 않으면 메서드를 정적으로 정의 할 수 있으며 개체와 독립적으로 사용할 수 있습니다.
정적 메서드 예
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
산출:
First String arg is: XYZ
Second String arg is: XYZ
위의 예제에서 볼 수 있듯이 정적 메서드를 호출하기 위해 객체를 사용하지 않았습니다. 프로그램에서 직접 호출하거나 클래스 이름을 사용하여 호출 할 수 있습니다.
비 정적 메서드 예제
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
산출:
I'm non-static method
비 정적 메서드는 항상 위의 예와 같이 클래스의 객체를 사용하여 호출됩니다.
키 포인트:
정적 메서드를 호출하는 방법 : 직접 또는 클래스 이름 사용 :
StaticDemo.copyArg(s1, s2);
또는
copyArg(s1, s2);
비 정적 메서드를 호출하는 방법 : 클래스의 객체 사용 :
Test obj = new Test();
기본적인 차이점은 비 정적 멤버는 'static'키워드를 사용하여 out으로 선언된다는 것입니다.
모든 정적 멤버 (변수와 메서드 모두)는 클래스 이름의 도움으로 참조됩니다. 따라서 클래스의 정적 멤버는 클래스 참조 멤버 또는 클래스 멤버라고도합니다.
클래스의 정적이 아닌 멤버에 액세스하려면 참조 변수를 만들어야합니다. 참조 변수는 객체를 저장합니다.
간단히 말해서, 사용자의 관점에서 정적 메서드는 변수를 전혀 사용하지 않거나 사용하는 모든 변수가 메서드에 로컬이거나 정적 필드입니다. 메서드를 정적으로 정의하면 약간의 성능 이점이 있습니다.
정적 방법에 대한 또 다른 시나리오입니다.
예, 정적 메서드는 개체가 아닌 클래스에 속합니다. 그리고 다른 사람이 클래스의 객체를 초기화하는 것을 원하지 않거나 둘 이상의 객체를 원하지 않는 경우에는 Private 생성자 와 정적 메서드 를 사용해야 합니다.
여기에는 개인 생성자가 있고 정적 메서드를 사용하여 개체를 만듭니다.
전의::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
데모 obj1 = Demo.createObj ();
여기서는 한 번에 하나의 인스턴스 만 살아 있습니다.
- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1
때로는 모든 개체에 공통적 인 변수를 원할 수 있습니다. 이것은 static modifier로 수행됩니다.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances
'Program Club' 카테고리의 다른 글
| 타이머를 어떻게 중지합니까? (0) | 2020.11.12 |
|---|---|
| Android ADT 오류, dx.jar이 SDK 폴더에서로드되지 않았습니다. (0) | 2020.11.12 |
| 시간 개체에 분 추가 (0) | 2020.11.12 |
| Swift에서 장치 방향 가져 오기 (0) | 2020.11.12 |
| 매개 변수가있는 신속한 GET 요청 (0) | 2020.11.12 |