zoukankan      html  css  js  c++  java
  • Java——this关键字总结

    一.this关键字的使用

    1.当同类型的对象a和b,调用相同的方法method()时,为了区分该方法是被a调用还是被b调用

      如下代码中,

    class Banana { void method(int i) { /* ... */ } }
    Banana a = new Banana(), b = new Banana();
    a.method(1);
    b.method(2);

      编译期内部的过程:

    1 Banana.method(a,1);
    2 Banana.method(b,2);

      方法的参数列表中的第一个参数即为调用该方法的对象的句柄(引用),编译期会以此来区分方法的调用

      可类比Python类中方法的关键字self,

    2.this 关键字(注意只能在方法内部使用)可为已调用了其方法的那个对象生成相应的句柄。可以向对待其他任

          何 对象句柄一样对待这个句柄。

      假如从本类中调用某一个方法时,可以省略this关键字,代码如下

    1 class Apricot {
    2 void pick() { /* ... */ }
    3 void pit() { pick(); /* ... */ }
    4 }

     this 关键字只能 用于那些特殊的类——需明确使用当前对象的句柄。例如,假若您希望将句柄返回给当前对 

        象,那么它经常在return 语句中使用。代码如下:

     1 public class Leaf {
     2     private int i = 0;
     3     Leaf increment() {
     4         i++;
     5         return this;
     6     }
     7         void print() {
     8         System.out.println("i = " + i);
     9     }
    10     public static void main(String[] args) {
    11         Leaf x = new Leaf();
    12         x.increment().increment().increment().print();
    13     }
    14 }        

      increment()通过 this 关键字返回当前对象的句柄,所以可以方便地对同一个对象执行多项操作

    3.this 关键字在构造函数中进行调用

      3.1 虽然可用this 调用构建函数,但同一个构造函数里不可调用两个。

      3.2 构造函数在类加载过程中是第一个进行加载的,否则会收到编译程序的报错信息

      3.3 可用 this来引用成员数据。经常都会在 Java 代码里看到这种应用,避免成员变量和方法参数之间的混淆

      3.4 编译器不容许从除了一个构建器之外的其他任何方法内部调用一个构造函数

      代码如下: 

     1 public class Flower {
     2     private int petalCount = 0;
     3     private String s = new String("null");
     4 
     5     Flower(int petals) {
     6         petalCount = petals;
     7         System.out.println("Constructor w/ int arg only petalCount="+ petalCount);
     8     }
     9     Flower(String ss) {
    10         System.out.println("Constructor w/ String arg only, s=" + ss);
    11         s = ss;
    12     }
    13 
    14     Flower(String s, int petals) {
    15         this(petals);
    16         // ! this(s); // Can't call two!
    17         this.s = s; // Another use of "this"
    18         System.out.println("String & int args");
    19     }
    20 
    21     Flower() {
    22         this("hi", 47);
    23         System.out.println("default constructor (no args)");
    24     }
    25 
    26     void print() {
    27         // ! this(11); // Not inside non-constructor!
    28         System.out.println("petalCount = " + petalCount + " s = " + s);
    29     }
    30 
    31     public static void main(String[] args) {
    32         Flower x = new Flower();
    33         x.print();
    34     }
    35 }
  • 相关阅读:
    Python自动化运维之1、Python入门
    Github使用教程
    Windows 托盘区域显示图标
    VS 2013 打包程序教程
    UML类图简单介绍
    crontab定时任务
    软硬链接的区别和重点
    linux运维之NFS服务器配置
    怎么样让Win10可以ping通?
    VM虚拟机Linux克隆后网卡的相关操作!
  • 原文地址:https://www.cnblogs.com/maria-ld/p/8571778.html
Copyright © 2011-2022 走看看