21xrx.com
2024-09-17 03:32:31 Tuesday
登录
文章检索 我的文章 写文章
Java中this关键字的使用实例
2023-06-15 20:44:23 深夜i     --     --
Java this关键字 引用当前对象 作为方法返回值 调用构造方法

在Java编程中,this关键字在实例化对象时常常使用。this关键字表示当前对象的引用。使用this可以很方便地对类的属性进行操作,同时也可以避免产生歧义。本文将通过几个实例详细介绍Java中this关键字的使用方法。

1. this关键字引用当前对象

在Java中,this关键字的第一个用法是引用当前对象。我们可以通过this引用当前对象的属性、方法等。例如:

public class Student{

  private String name;

  public Student(String name)

    this.name = name;

  public void setName(String name)

    this.name = name;

}

在上述代码中,this.name表示当前对象的name属性。

2. this关键字作为方法返回值

this关键字还可以作为方法返回值。这里的this表示方法所在的当前对象。例如:

public class Student{

  //...

  public Student getStudent()

    return this;

}

在上述代码中,getStudent()方法返回的是当前对象。

3. this关键字调用构造方法

在Java中,this还可以用于调用构造方法。例如:

public class Student{

  private String name;

  private int age;

  public Student(){

    this("unknown", 0);

  }

  public Student(String name, int age)

    this.name = name;

    this.age = age;

}

在上述代码中,Student()方法中的this("unknown", 0)调用了Student(String name, int age)构造方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章