zoukankan      html  css  js  c++  java
  • JAVA

    ps:为什么感觉我学不会java了。

     this最常的用法:

      1.  在程序中产生二义性之处,应使用this来指明当前对象;普通方法中,this总是指向调用该方法的对象。构造方法中,this总是指向正要初始化的对象。

      2. 使用this关键字调用重载的构造方法,避免相同的初始化代码。但只能在构造方法中用,并且必须位于构造方法的第一句。

      3. this不能用于static方法中。

    this代表“当前对象”:

     1 public class User {
     2     int id;        //id
     3     String name;   //账户名
     4     String pwd;   //密码
     5 
     6     public User() {
     7     }
     8 
     9     public User(int id, String name) {
    10         System.out.println("正在初始化已经创建好的对象:" + this);
    11         this.id = id;   //不写this,无法区分局部变量id和成员变量id
    12         this.name = name;
    13     }
    14 
    15     public void login() {
    16         System.out.println(this.name + ",要登录!");  //不写this效果一样
    17     }
    18 
    19     public static void main(String[] args) {
    20         User u3 = new User(101, "高小七");
    21         System.out.println("打印高小七对象:" + u3);
    22         u3.login();
    23     }
    View Code

    this调用重载构造方法:

     1 public class TestThis {
     2     int a, b, c;
     3 
     4     TestThis() {
     5         System.out.println("正要初始化一个Hello对象");
     6     }
     7 
     8     TestThis(int a, int b) {
     9         // TestThis(); //这样是无法调用构造方法的!
    10         this(); // 调用无参的构造方法,并且必须位于第一行!
    11         a = a;// 这里都是指的局部变量而不是成员变量
    12 // 这样就区分了成员变量和局部变量. 这种情况占了this使用情况大多数!
    13         this.a = a;
    14         this.b = b;
    15     }
    16 
    17     TestThis(int a, int b, int c) {
    18         this(a, b); // 调用带参的构造方法,并且必须位于第一行!
    19         this.c = c;
    20     }
    21 
    22     void sing() {
    23     }
    24 
    25     void eat() {
    26         this.sing(); // 调用本类中的sing();
    27         System.out.println("你妈妈喊你回家吃饭!");
    28     }
    29 
    30     public static void main(String[] args) {
    31         TestThis hi = new TestThis(2, 3);
    32         hi.eat();
    33     }
    34 }
    View Code
  • 相关阅读:
    高斯函数 and 对数高斯函数 拟合曲线
    Python3.6、3.7、3.8新特性
    常用限流策略——漏桶与令牌桶介绍
    常用的HTTP服务压测工具介绍
    使用swagger生成接口文档
    validator库参数校验若干实用技巧
    树形结构数据处理
    element-ui 抽屉组件(el-drawer ) 二次封装 增加resize拖曳改变宽度大小
    pm2常用命令
    vue3-- setup中获取数组dom
  • 原文地址:https://www.cnblogs.com/OFSHK/p/12958138.html
Copyright © 2011-2022 走看看