在Java中,this和this()都是完全不同的。

  • this关键字用来指代当前对象,即通过它来调用方法。
  • this()是用来从同一类别的另一个构造函数中调用一个构造函数。

下表显示了this关键字和this()之间点对点的区别。

this this()
this关键字只用于对象。this指的是当前对象。 this()只用于构造函数。
它指的是同一类的构造函数 其参数与传递给this(参数)的参数一致。
Dot(.)操作符用于访问成员。例如,this.variableName; 没有使用Dot(.)操作符。只有匹配的参数被传递。
this关键字用于区分方法中的局部变量和实例变量。 this()被用来指代属于同一类别的构造函数。

请看下面的代码,它描述了对this个关键字的使用。

import java.io.*;

public class Student {

    private String name;
    private int age;

    public Student(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public void show()
    {
        System.out.println("Name = " + this.name);
        System.out.println("Age = " + this.age);
    }

    public static void main(String[] args)
    {
        // Creating new instance of Student Class
        Student student = new Student("Yiibai", 23);
        student.show();
    }
}

运行结果:

Name = Yiibai
Age = 23

现在看一下下面的代码,它描述了this()的使用。

import java.io.*;

public class Student {

    private String name;
    private int age;

    // Constructor 1 with String as parameter.
    public Student(String name)
    {
        // This line of code calls the second constructor.
        this(23);
        System.out.println("Name of Student : " + name);
    }

    // Constructor 2 with int in parameter.
    public Student(int age)
    {
        System.out.println("Age of student = " + age);
    }

    // Constructor 3 with no parameters.
    public Student()
    {
        // This line calls the first constructor.
        this("Yiibai.com");
    }

    public static void main(String[] args)
    {
        // This calls the third constructor.
        Student student = new Student();
    }
}

运行结果:

Age of student = 23
Name of Student : Yiibai.com

请注意,this()应该始终是构造函数中的第一个可执行语句。否则,程序会在编译时出错。

| ——- | ——- | ——- |

Java中this和this()的区别

欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果。
转载请注明:文章转载自 有区别网 [http://www.vsdiffer.com]
本文标题:Java中this和this()的区别
本文链接:https://www.vsdiffer.com/vs/difference-between-this-and-this-in-java.html
免责声明:以上内容仅代表 个人看法、理解、学习笔记、总结和研究收藏。不保证其正确性,因使用而带来的风险与本站无关!如本网站内容冒犯了您的权益,请联系站长,邮箱: ,我们核实并会尽快处理。