zoukankan      html  css  js  c++  java
  • (二)《Java编程思想》——t h i s 关键字

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

    package chapter4;
    
    //: Leaf.java
    // Simple use of the "this" keyword
    public class Leaf {
        private int i = 0;
    
        Leaf increment() {
            i++;
            return this;
        }
    
        void print() {
            System.out.println("i = " + i);
        }
    
        public static void main(String[] args) {
            Leaf x = new Leaf();
            x.increment().increment().increment().print();
        }
    } // /:~

    【运行结果】:i = 3
    在构建器里调用构建器

    package chapter4;
    
    //: Flower.java
    // Calling constructors with "this"
    public class Flower {
        private int petalCount = 0;
        private String s = new String("null");
    
        Flower() {
            this("hi", 47);
            System.out.println("default constructor (no args)");
        }
    
        Flower(int petals) {
            petalCount = petals;
            System.out.println("Constructor w/ int arg only, petalCount= " + petalCount);
        }
    
        Flower(String ss) {
            System.out.println("Constructor w/ String arg only, s=" + ss);
            s = ss;
        }
    
        Flower(String s, int petals) {
            this(petals);
            // ! this(s); // Can't call two!
            this.s = s; // Another use of "this"
            System.out.println("String & int args");
        }
    
        void print() {
            // ! this(11); // Not inside non-constructor!
            System.out.println("petalCount = " + petalCount + " s = " + s);
        }
    
        public static void main(String[] args) {
            Flower x = new Flower();
            x.print();
        }
    } // /:~

    【运行结果】:

    Constructor w/ int arg only, petalCount= 47
    String & int args
    default constructor (no args)
    petalCount = 47 s = hi

    this调用构建器要注意几点:

    1.它会对与那个自变量列表相符的构建器进行明确的调用。

    2.只能在一个构建器中使用this调用另一个构建器,不能在其他任何方法内部使用。

    3.this调用构建器必须写在第一行,否则会收到编译程序的报错信息。

    4.在一个构建器中不能两次使用this调用其他构建器(即与第三条相符)。

  • 相关阅读:
    weblogic12c 2021.4.20 季度补丁 SPB
    一顿debug猛如虎,原来内存OOM
    JDK记录一下
    213. 打家劫舍 II-动态规划-中等
    5526. 最多可达成的换楼请求数目-回溯-困难
    1584. 连接所有点的最小费用-图/最小生成树-中等
    Java-泛型的限制
    Java-泛型-桥方法
    889. 根据前序和后序遍历构造二叉树-树-中等
    1109. 航班预订统计-差分数组-中等
  • 原文地址:https://www.cnblogs.com/echolxl/p/3167198.html
Copyright © 2011-2022 走看看