zoukankan      html  css  js  c++  java
  • JAVA中this关键字的用法

    this关键字主要有三个应用:

    1.调用本类中的属性,也就是类的成员变量;

    2.调用本类中的其他方法;

    3.调用本类中的其他构造方法,调用时候要放在构造方法的首行。

    * this关键词除了可以调用变量或者成员方法之外,最引人注目的是它可以返回类的引用。如在本类中使用return this ,即可返回对类的引用。如代码在student类上,那么return this 即代表着return student。

    *------------------------------------------------------------------------------------------------------------------------------------分割线——————————————————————————————————————————————————————————*

    java中构造方法的特性:

    • 当前类的其他构造方法通过this语句调用;
    • 当前类的子类的构造方法通过super语句调用;
    • 在程序中通过new语句调用。

     *------------------------------------------------------------------------------------------------------------------------------------分割线——————————————————————————————————————————————————————————*

    参考文档 :http://www.cnblogs.com/nolonely/p/5916602.html

    1.当成员变量和局部变量重名的时候,在方法中使用this则代表的是类的成员变量。

    2.把自己当作参数传递时,也可以用this.(this作当前参数进行传递)

    3.有时候,我们会用到一些内部类和匿名类,如事件处理。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。如:

    public class HelloB {
        int i = 1;
     
        public HelloB() {
           Thread thread = new Thread() {
               public void run() {
                  for (int j=0;j<20;j++) {
                      HelloB.this.run();//调用外部类的方法
                      try {
                         sleep(1000);
                      } catch (InterruptedException ie) {
                      }
                  }
               }
           }; // 注意这里有分号
           thread.start();
        }
     
        public void run() {
           System.out.println("i = " + i);
           i++;
        }
       
        public static void main(String[] args) throws Exception {
           new HelloB();
        }
    }
    

    4.在构造函数中,通过this可以调用同一类中别的构造函数。如:

    public class Test{
      private static String b = "dsd";
      
      public Test(){
        this(b);
        
      }
      
      public Test(String a){
        System.out.println(a);
      }
      
    }
    

    5.this同时传递多个参数

    public class TestClass {
        int x;
        int y;
     
        static void showtest(TestClass tc) {//实例化对象
           System.out.println(tc.x + " " + tc.y);
        }
        void seeit() {
           showtest(this);
        }
     
        public static void main(String[] args) {
           TestClass p = new TestClass();
           p.x = 9;
           p.y = 10;
           p.seeit();
        }
    }
    

      

  • 相关阅读:
    linux目录结构介绍
    Linux下安装Redis
    SpringBoot启动器详解pom.xml
    Linux(CentOS6.X)安装mysql
    CentOS 7 安装 MySQL
    GIT和SVN的区别
    SourceTree安装教程
    Git版本控制软件结合GitHub从入门到精通常用命令学习手册
    WIN下Git GUI 教程
    把文件(项目)上传到Git@OSC
  • 原文地址:https://www.cnblogs.com/ycmxm/p/7026868.html
Copyright © 2011-2022 走看看