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

    成员方法中的this

      指当前类对象

      更准确的说法是指调用该成员方法的对象

    public class People {
        String name;
        int age;
        
        //this表示当前类对象,谁调用就指代谁
        public void setNameAndAge() {
            this.name = "李四";
            this.age = 28;        
    //        age = 300;//省略了this,最好不要这样写
        }
        
        public void setAge(int age) {
            this.age = age;    //区分了成员变量和局部变量
        }
        
        //使用this调用成员方法
        public void test() {
            this.setAge(100);
        }
    }
    public class Test {
        public static void main(String[] args) {
            People p = new People();
            System.out.println("姓名:" + p.name + ",年龄:" + p.age);
            p.setNameAndAge();
            System.out.println("姓名:" + p.name + ",年龄:" + p.age);
            p.test();
            System.out.println("姓名:" + p.name + ",年龄:" + p.age);
        }
    }

    this可被当作实例方法或类方法的实参和返回值

    public class Dog {
        //类的类型作为参数
        public void eat(Dog d) {
            
        }
        //this作为实参,表示调用该方法的对象
        public void test() {
            System.out.println(this);
            this.eat(this);
        }
        //this作为返回值,表示返回调用该方法的对象
        public int age = 0;
        public Dog sleep() {
            age++;
            return this;
        }
    }
    public class Test {
        public static void main(String[] args) {
            Dog d = new Dog();
            d.test();
            System.out.println(d);
             
            Dog g1 = new Dog();
            System.out.println(g1);
            Dog g2 = g1.sleep();
            System.out.println(g2);
            System.out.println(g2.age);
            Dog g3 = g1.sleep()
                        .sleep()
                            .sleep();
            System.out.println(g3.age);    
        }
    }

    this还可用于构造方法中

  • 相关阅读:
    如何选择大数据应用程序
    Python字符和字符值(ASCII或Unicode码值)转换方法
    Python字符和字符值(ASCII或Unicode码值)转换方法
    论炒币者的自我修养
    论炒币者的自我修养
    区块链是什么,如何评价区块链
    C#封装C++DLL(特别是char*对应的string)
    C#文件夹和文件操作
    VS工程目标文件名设置
    double最大最小值宏定义
  • 原文地址:https://www.cnblogs.com/lialong1st/p/7907216.html
Copyright © 2011-2022 走看看