산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 이 키워드

자바 이 키워드

이 기사에서는 Java에서 이 키워드를 사용하는 방법과 위치에 대해 예제를 통해 배웁니다.

이 키워드

Java에서 이 키워드는 메소드 또는 생성자 내부의 현재 객체를 참조하는 데 사용됩니다. 예를 들어,

class Main {
    int instVar;

    Main(int instVar){
        this.instVar = instVar;
        System.out.println("this reference = " + this);
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("object reference = " + obj);
    }
}

출력 :

this reference = Main@23fc625e
object reference = Main@23fc625e

위의 예에서는 obj라는 개체를 만들었습니다. 메인 클래스의 . 그런 다음 obj 개체에 대한 참조를 인쇄합니다. 및 this 클래스의 키워드입니다.

여기에서 objthis 는 똑같은. 이는 현재 개체에 대한 참조일 뿐임을 의미합니다.

<시간>

이 키워드의 사용

this 키워드가 일반적으로 사용됩니다.

모호한 변수 이름에 사용

Java에서는 범위(클래스 범위 또는 메서드 범위) 내에서 동일한 이름을 가진 두 개 이상의 변수를 선언할 수 없습니다. 그러나 인스턴스 변수와 매개변수는 같은 이름을 가질 수 있습니다. 예를 들어,

class MyClass {
    // instance variable
    int age;

    // parameter
    MyClass(int age){
        age = age;
    }
}

위의 프로그램에서 인스턴스 변수와 매개변수의 이름은 나이가 같습니다. 여기에서 Java 컴파일러는 이름 모호성으로 인해 혼동됩니다.

이러한 상황에서 이 키워드를 사용합니다. 예를 들어,

먼저 this을 사용하지 않은 예를 보겠습니다. 키워드:

class Main {

    int age;
    Main(int age){
        age = age;
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("obj.age = " + obj.age);
    }
}

출력 :

obj.age = 0

위의 예에서는 8을 전달했습니다. 생성자에 대한 값으로. 그러나 0 출력으로. 이는 인스턴스 변수와 매개변수 사이의 이름이 모호하여 Java 컴파일러가 혼동되기 때문입니다.

이제 this을 사용하여 위의 코드를 다시 작성해 보겠습니다. 키워드.

class Main {

    int age;
    Main(int age){
        this.age = age;
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("obj.age = " + obj.age);
    }
}

출력 :

obj.age = 8

이제 예상 출력을 얻고 있습니다. 생성자가 호출될 때 this이기 때문입니다. 생성자 내부는 obj 개체로 대체됩니다. 생성자를 호출한 것입니다. 따라서 나이 변수에 할당된 값 8 .

또한 매개변수와 인스턴스 변수의 이름이 다른 경우 컴파일러는 자동으로 이 키워드를 추가합니다. 예를 들어, 코드:

class Main {
    int age;

    Main(int i) {
        age = i;
    }
}

는 다음과 같습니다.

class Main {
    int age;

    Main(int i) {
        this.age = i;
    }
}
<시간>

게터 및 세터 사용

this의 또 다른 일반적인 용도 키워드는 setters 및 getters 메서드에 있습니다. 클래스의. 예:

class Main {
   String name;

   // setter method
   void setName( String name ) {
       this.name = name;
   }

   // getter method
   String getName(){
       return this.name;
   }

   public static void main( String[] args ) {
       Main obj = new Main();

       // calling the setter and the getter method
       obj.setName("Toshiba");
       System.out.println("obj.name: "+obj.getName());
   }
}

출력 :

obj.name: Toshiba

여기에서는 this을 사용했습니다. 키워드:

<시간>

생성자 오버로딩에서 사용

생성자 오버로딩으로 작업하는 동안 다른 생성자에서 하나의 생성자를 호출해야 할 수도 있습니다. 이러한 경우 생성자를 명시적으로 호출할 수 없습니다. 대신 this을 사용해야 합니다. 키워드.

여기에서는 이 키워드의 다른 형식을 사용합니다. 즉, this() . 예를 들어 보겠습니다.

class Complex {

    private int a, b;

    // constructor with 2 parameters
    private Complex( int i, int j ){
        this.a = i;
        this.b = j;
    }

    // constructor with single parameter
    private Complex(int i){
        // invokes the constructor with 2 parameters
        this(i, i); 
    }

    // constructor with no parameter
    private Complex(){
        // invokes the constructor with single parameter
        this(0);
    }

    @Override
    public String toString(){
        return this.a + " + " + this.b + "i";
    }

    public static void main( String[] args ) {
  
        // creating object of Complex class
        // calls the constructor with 2 parameters
        Complex c1 = new Complex(2, 3); 
    
        // calls the constructor with a single parameter
        Complex c2 = new Complex(3);

        // calls the constructor with no parameters
        Complex c3 = new Complex();

        // print objects
        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
    }
}

출력 :

2 + 3i
3 + 3i
0 + 0i

위의 예에서는 this을 사용했습니다. 키워드,

줄을 주목하십시오.

System.out.println(c1);

여기서 c1 객체를 인쇄할 때 , 객체는 문자열로 변환됩니다. 이 과정에서 toString() 라고 합니다. toString()을 재정의하므로 클래스 내부의 메서드에서 해당 메서드에 따라 출력을 얻습니다.

this()의 큰 장점 중 하나 중복 코드의 양을 줄이는 것입니다. 그러나 this()를 사용할 때는 항상 주의해야 합니다. .

다른 생성자에서 생성자를 호출하면 오버헤드가 추가되고 프로세스가 느리기 때문입니다. this() 사용의 또 다른 큰 이점 중복 코드의 양을 줄이는 것입니다.

참고 :다른 생성자에서 하나의 생성자를 호출하는 것을 명시적 생성자 호출이라고 합니다.

<시간>

이를 인수로 전달

this을 사용할 수 있습니다. 현재 개체를 메서드에 대한 인수로 전달하는 키워드입니다. 예를 들어,

class ThisExample {
    // declare variables
    int x;
    int y;

    ThisExample(int x, int y) {
       // assign values of variables inside constructor
        this.x = x;
        this.y = y;

        // value of x and y before calling add()
        System.out.println("Before passing this to addTwo() method:");
        System.out.println("x = " + this.x + ", y = " + this.y);

        // call the add() method passing this as argument
        add(this);

        // value of x and y after calling add()
        System.out.println("After passing this to addTwo() method:");
        System.out.println("x = " + this.x + ", y = " + this.y);
    }

    void add(ThisExample o){
        o.x += 2;
        o.y += 2;
    }
}

class Main {
    public static void main( String[] args ) {
        ThisExample obj = new ThisExample(1, -2);
    }
}

출력 :

Before passing this to addTwo() method:
x = 1, y = -2
After passing this to addTwo() method:
x = 3, y = 0

위의 예에서 ThisExample() 생성자 내부 , 줄을 주목하십시오.

add(this);

여기에서는 add()를 호출합니다. 이것을 인수로 전달하여 메서드. 이 키워드에는 obj 개체에 대한 참조가 포함되어 있기 때문에 클래스의 x 값을 변경할 수 있습니다. 및 y add() 내부 방법.


java

  1. C# 이 키워드
  2. 자바 연산자
  3. 자바 주석
  4. 자바 for-each 루프
  5. 자바 생성자
  6. 자바 문자열
  7. 자바 이 키워드
  8. 자바 최종 키워드
  9. 자바 인터페이스
  10. 자바 캡슐화