Java is a keyword

I read that in Java you do not need to explicitly bind this to the object, this is done by the interpreter. This is the opposite of Javascript, where you always need to know the meaning of this . But where does this in Java indicate - a class or an object? Or is it changing? This question is part of my attempt to understand the basic concepts of OO and design patterns, so I can apply them to Javascript. Thank.

+3
source share
6 answers

Java language specification :

When used as the main expression, the this keyword denotes a value; it is a reference to an object for which the instance method has been called (§15.12) or for an object that is being built.

those. it always points to an object, not a class.

+2
source

In Java, it thisalways refers to an object and never to a class.

+9
source

this .

- , . , .

+2

java this is refer Current object

public class Employee{

String name,adress;

Employee(){

 this.name="employee";
 this.address="address";

}

}
+1

java 'this' , . setter 'this' .

public class Person {

  String name;
  int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public static void main(String[] args) {
    Person p = new Person();
    p.setName("Rishi");
    p.setAge(23);
    System.out.println(p.getName() + " is " + p.getAge() + " years old");
  }
}
+1

( ):

this - , . , .

, , this, , .

As a note, you cannot use thiswith static fields or methods because they do not belong to any particular object (an instance of the class).

0
source

All Articles