zoukankan      html  css  js  c++  java
  • this 关键字的使用及说明

    this 是Java 中常见的一个关键字,它的主要作用是引用类的当前实例,本篇文章主要介绍 this 关键字的几种使用情况。

    1. this 调用当前类的变量,也就是类中的成员变量。

    代码示例:

    public class Student {
    
        private String name="张三";
    
        public void testName(String name){
            System.out.println("局部变量name的值为:" + name);
            System.out.println("成员变量name的值为:" + this.name);
        }
    
    }
    public static void main(String[] args) {
    
            Student student = new Student();
            student.testName("李四");
    
        }

    运行结果:

    局部变量name的值为:李四
    成员变量name的值为:张三

    2. this 调用当前类的其它方法,也就是类中的成员方法。

    代码示例:

    public class Student {
    
        private String name="张三";
    
        public void testName(){
            this.haha();
        }
    
        public void haha(){
            System.out.println(" this 调用当前类的其它方法 ");
        }
    
    }
    public static void main(String[] args) {
    
            Student student = new Student();
            student.testName();
    
        }

    运行结果:

     this 调用当前类的其它方法 

    3. this 调用当前类的构造方法。

    当使用 this 关键字在当前类的构造器中调用当前类的其它构造方法时,this 需要放在当前构造器的首行,不然会编译报错。

    代码示例:

    public class Student {
    
        public Student(){
            System.out.println("构造方法一");
        }
    
        public Student(String name){
            this();   //放在首行
            System.out.println("构造方法二");
        }
    
    }
    public static void main(String[] args) {
    
            Student student = new Student("张三");
    
        }

    运行结果:

    构造方法一
    构造方法二

    如果 this 不放在首行,编译期将会报错。

    如果在当前类的普通方法中使用 this 调用类的构造器,同样会报错。

     

    一些其它说明:

    this 不能用在 static 修饰的方法中,因为被 static 修饰的方法属于类,不属于这个类的某个对象,而 this 代表当前类对象的引用,指向一个具体的对象。

  • 相关阅读:
    知行合一与做人
    根基不牢 地动山摇
    不要放过任何问题
    关于php存储cookie时path存放路径放的详细介绍
    通过JiaThis API接口自定义分享功能按钮实现分享功能本地化
    windows下如何创建没有名字的.htaccess文件
    PHP编程效率的20个要点
    分享如何使用PHP将URL地址参数进行加密传输提高网站安全性
    url加密,一般只对参数加密
    encodeURIComponent() 函数
  • 原文地址:https://www.cnblogs.com/hs2018/p/10168142.html
Copyright © 2011-2022 走看看