码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • Java this 关键字


    目录

    一、this 在实例方法中使用

    二、this 构造方法中调用其他构造方法

    三、小结


            this 在实例方法中使用,代表当前对象。

             this 在构造方法中调用其他构造方法,必须在构造方法第一行。

    一、this 在实例方法中使用

           格式: this.

    1. public class Person {
    2. private String name;
    3. private int age;
    4. public Person(String name, int age) { // 构造方法
    5. this.name = name; // this 代表当前对象
    6. this.age = age; // this 代表当前对象
    7. //name = name; // 省略this写法
    8. //age = age; // 省略this写法
    9. }
    10. public void say() { // 普通方法
    11. System.out.println("name ="+this.name+" age="+this.age); // this代表当前对象
    12. System.out.println("name ="+name+" age="+age); // 省略this写法
    13. }
    14. public static void main(String[] args) {
    15. Person person = new Person("张三", 18);
    16. person.say();
    17. }
    18. }

    二、this 构造方法中调用其他构造方法

              语法: this (实参)

    1. public class Person {
    2. private String name;
    3. private int age;
    4. public Person(String name) {// 构造方法
    5. this.name = name;
    6. }
    7. public Person(String name, int age) { // 构造方法
    8. this(name); // 调用其他构造方法必须放在第一行,不然编译不通过
    9. this.age = age;
    10. }
    11. public void say() { // 普通方法
    12. System.out.println("name ="+this.name+" age="+this.age); // this代表当前对象
    13. }
    14. public static void main(String[] args) {
    15. Person person = new Person("张三", 18);
    16. person.say();
    17. }
    18. }

    三、小结

            this 不能使用在带有 static 的方法当中。因为 this 表示当前对象,所属对象,而被 static 修饰方法所属类,对象的产生是先有类。

  • 相关阅读:
    数据库复制:Spectral Core Full Convert Ultimate 2022
    软考高级(信息系统项目管理师)高频考点-项目管理计划
    自学考试到底难不难?
    2.3.13、head:显示文件开头的内容
    OpenShift 4 - 定制 RHACS 安全策略,阻断生产集群使用高风险 Registry
    LeetCode 1710. 卡车上的最大单元数
    VSCode开启Pull Request更新代码分支可视化新篇章
    软件测试周刊(第84期):这个世界根本不存在“不会做”、“不能做”,只有“不想做”和“不敢做”,当你失去所有依靠的时候,你自然就什么都会了。
    c++使用googletest进行单元测试
    竞赛选题 深度学习卷积神经网络的花卉识别
  • 原文地址:https://blog.csdn.net/u012965203/article/details/127716876
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号