java中this关键字的认识

2021/10/22 20:39:54

本文主要是介绍java中this关键字的认识,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java中this关键字的认识
this关键字的三种用法

一,this修饰属性
this修饰成员变量,表示直接使用类中的成员变量
例如:

class Person{
  private String name;
  private int age;
  public Person(String name,int age){
    this.name = name;//this修饰属性
    this.age = age;
  }
 }

二,this修饰方法
1,this调用类中的成员方法
例如:

class Person{
  private String name;
  private int age;
  public void fun(){
    int a = 10;
    this.sun();//this调用成员方法
    sun();//默认会加上this
  }
   public void sun(){
   //调用属性,默认在属性前面加this
    System.out.println("hahaha");
  }
 }

2,this调用构造方法
(1)语法
this(构造方法参数列表)
(2)当在构造方法中调用其他构造方法时,此时语句写在构造方法的首行
例如:

class Person{
   private String name;
   private int age; //属性
   private int sex;
  public Person(){ //无参构造方法
    System.out.println("haha")
  }
  public Person(String name,int age){
    this(); //this调用无参构造方法
    this.name = name;//this修饰属性
  }
   public Person(String name,int age,int sex){
    this(name,age); //this调用两个参数构造方法
    this.sex = sex;//this修饰属性
  }
 }

3,构造方法调用是线性的,不能是环

三,this表示当前对象的引用
例如:

class Person{
  private String name;//属性
  private int age;
  public void fun(){
  //this表示当前对象的引用
  System.out.println(this);
  }
 }
 public class Test{
   public static void main(String[] args){
     Person p1 = new Person();//对象p1
     System.out.println(p1);
     p1.fun();//this 表示对象p1的引用
     Person p2 = new Person();//对象p2
     System.out.println(p2);
     p2.fun();//this 表示对象p2的引用
   }
 }


这篇关于java中this关键字的认识的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程