Java中关于this的一点疑问

偶然翻以前的笔记时发现,this使用在构造方法和实例方法中可以缺省,而this又不能用于类方法中。这是否意味着this在方法中没有存在的必要?又或者别的?

this。可以使用在类方法中。
比如set方法。不就使用了this。

我理解错了么?

this用在成员函数。成员变量中。类函数属于类。不属于实例。没有this概念

this主要是类内部使用例如你说set函数里面一般都是this.a=a;之类的。所以还是有存在的必要,没有this就无法区分传入函数的变量和类成员了

this主要是为了区分作用域的。

this作为Java语言的一个关键字,有其适用的场景:
1.当出现同名冲突时,表明引用的是成员变量(field)。
2.整体上指代类的某个实例对象。
3.在构造函数中调用其它构造函数。

如果定义了如下类

 public class MyThisTest {
  private int a;

  public MyThisTest() {
    this(42); // calls the other constructor
  }

  public MyThisTest(int a) {
    this.a = a; // assigns the value of the parameter a to the field of the same name
  }

  public void frobnicate() {
    int a = 1;

    System.out.println(a); // refers to the local variable a
    System.out.println(this.a); // refers to the field a
    System.out.println(this); // refers to this entire object
  }

  public String toString() {
    return "MyThisTest a=" + a; // refers to the field a
  }
}

当new MyThisTest()生成类实例,并调用frobnicate,其输出结果为:
1
42
MyThisTest a=42

this不用在成员方法省略,但是楼主想一想当你调用成员方法时,是不是用 对象.method 来调用的。
所以this代指的是调用该方法的对象。
this在方法内部也是代指调用该方法的对象。
通过this可以准确地表示要在函数中使用的变量和方法是哪个对象的。