• (二)《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调用其他构建器(即与第三条相符)。

  • 相关阅读:
    下载windows原装镜像的官方网站
    Typora快捷键
    UOS使用ZSH终端教程
    UOS每日折腾、调教、美化
    AMD64和X86_64
    CPU架构
    23种设计模式---单例设计模式(精华)
    java学习day32-Servlet上下文--ServletContext
    java学习day32-Servlet过滤器-Filter
    java学习day32-JSP标签技术-JSTL标签库
  • 原文地址:https://www.cnblogs.com/echolxl/p/3167198.html
Copyright © 2020-2023  润新知