栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java中this的两个作用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java中this的两个作用

什么是 this 引用: java 编译器给每个 “ 成员方法 “ 增加了一个隐藏的引用类型参数,该引用参数指向当前对象 ( 成员方法运行 时调用该成员方法的对象 ) ,在成员方法中所有成员变量的操作,都是通过该引用去访问 。只不过所有的 操作对用户是透明的,即用户不需要来传递,编译器自动完成。

this一共有两个作用:

第一个作用:this就是一个引用,类型就是当前类。

class Person(){ this  类型就是Person}

class Cat(){this 类型就是Cat}

指向当前对象,构造器中this指向的就是当前正在构造的对象。

this.属性                 此时一定是属性的全名。

第二个作用:在一个构造方法中调用其他构造方法。

package mjh.week.day5;

public class Test2 {
    Test2() {
        this(18);
        System.out.println("无参");
    }

    Test2(int a) {
        System.out.println("int");
    }

    Test2(String b) {
        System.out.println("string");
    }

    public static void main(String[] args) {
        new Test2();
    }
}
this 引用的特性 1. this 的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型 2. this 只能在 " 成员方法 " 中使用 3. 在 " 成员方法 " 中, this 只能引用当前对象,不能再引用其他对象,具有 final 属性 4. this 是 “ 成员方法 ” 第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this 负责来接收。
package mjh.week.day5;

public class Date {
    public int year;
    public int month;
    public int day;

    public void setDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate() {
        System.out.println(this.year + "/" + this.month + "/" + this.day);
    }

    public static void main(String[] args) {
        Date d = new Date();
        d.setDate(2021, 12, 28);
        d.printDate();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683928.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号