• Java学习 --- this关键字


    目录

    一、this是什么

    二、this的本质

    三、this的注意事项


    一、this是什么

    Java虚拟机会给每个对象分配this,代表当前对象。

    示例代码

    1. public class Constructor02 {
    2. public static void main(String[] args) {
    3. Person person = new Person("tom");
    4. person.info();
    5. }
    6. }
    7. class Person{
    8. String name;
    9. public Person(String name) {
    10. //this.name表示当前对象的属性
    11. this.name = name;
    12. }
    13. public void info(){
    14. System.out.println("name的信息:"+name);
    15. }
    16. }

    二、this的本质

    内存图 

     使用hashCode方法验证

    public class Constructor02 {
        public static void main(String[] args) {
            Person person = new Person("tom");
            System.out.println("person.name的hashCode() = " + person.name.hashCode());
        }
    }
    class Person{
        String name;
    
        public Person(String name) {
            //this.name表示当前对象的属性
            this.name = name;
            System.out.println("this.name的hashCode的为"+this.name.hashCode());
        }
        public void info(){
            System.out.println("name的信息:"+name);
        }
    }

     

     总结:那个对象调用,this就代表那个对象

    三、this的注意事项

    1、this关键字可以用来访问本类的属性、方法、构造器。

    2、this用于区分当前类的属性和局部变量

    3、访问成员方法:this.方法名(参数列表)

    public class This01 {
        public static void main(String[] args) {
            T t = new T();
            t.a2();
        }
    }
    class T{
        public void a1(){
            System.out.println("a1方法被调用");
        }
        public void a2(){
            System.out.println("a2方法被调用");
            //使用this调用方法
            this.a1();
        }
    }

    4、访问构造器方法:this(参数列表);只能在构造器中使用,this语句必须为第一行

    1. public class This01 {
    2. public static void main(String[] args) {
    3. T t = new T();
    4. }
    5. }
    6. class T{
    7. String name;
    8. public T() {
    9. //使用this调用构造方法,this必须在第一行
    10. this("tom");
    11. System.out.println("T类的无参构造器被调用");
    12. }
    13. public T(String name) {
    14. this.name = name;
    15. System.out.println("T类的有参构造器被调用");
    16. }
    17. }

     5、this不能在类定义的外部使用,只能在类定义的方法中使用。

      

  • 相关阅读:
    (Spring笔记)SpringBoot+Mybatis+Sqlite3查询表数据
    基于强化学习的测试日志智能分析实践
    Mysql之增删改查
    【C++】模板
    介绍几个语言生成的预训练模型
    vue修饰符的用法
    死磕面试系列,Java到底是值传递还是引用传递?
    GIS开发入坑(二)--ArcGIS影像切片并使用GeoServer发布
    安全防御——防火墙二
    盛唐诗人三杰,儒释道的代表
  • 原文地址:https://blog.csdn.net/qq_46093575/article/details/126743023