• Java 中的this关键字


    1.this关键字代表当前对象

      this.属性  操作当前对象的属性

      this.方法  调用当前对象的方法

    2.封装对象的属性的时候,经常会使用this关键字

    public class Telphone {
        private float screen;
        private float cpu;
        private float mem;
        
        public void sendMessage(){
            System.out.println("sendMessage");
        }
        
        public float getScreen() {
            return screen;
        }
        public void setScreen(float screen) {
            this.screen = screen; // 操作当前对象的属性
            this.sendMessage();      // 调用当前对象的方法
        }
        public float getCpu() {
            return cpu;
        }
        public void setCpu(float cpu) {
            this.cpu = cpu;
        }
        public float getMem() {
            return mem;
        }
        public void setMem(float mem) {
            this.mem = mem;
        }
        public Telphone(){
            System.out.println("com.imooc.Telphone");
        }
        public Telphone(float newScreen,float newCpu,float newMem){
            if(newScreen<3.5f){
                System.out.println("...............");
                screen = 3.5f;
            }
            cpu = newCpu;
            mem = newMem;
            System.out.println("----------------");
        }
    }

    this

    this 是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个指针

    this 的用法在 Java 中大体可以分为3种:

    1.普通的直接引用

    这种就不用讲了,this 相当于是指向当前对象本身。

    2.形参与成员名字重名,用 this 来区分:

    package s2;
    
    class Person {
        private int age = 22;
        public Person() {
            System.out.println("初始化年龄:" + age);
        }
        
        public int getAge(int age) {
            this.age = age;  // 形参与成员名字重名
            return this.age;
        }
    }
    
    public class Test03 {
        public static void main(String[] args) {
            Person Harry = new Person();
            System.err.println("Harry's age is:" + Harry.getAge(33));
        }
    }

    运行结果:

    初始化年龄:22
    Harry's age is:33

    3.引用构造函数

    这个和 super 放在一起讲,见下面

  • 相关阅读:
    单细胞分析实录(13): inferCNV结合UPhyloplot2分析肿瘤进化
    单细胞分析实录(12): 如何推断肿瘤细胞
    单细胞分析实录(11): inferCNV的基本用法
    用网络图展示富集分析
    R绘图(6): 拯救初学者——发表级绘图全能包ggpubr
    R绘图(5): 一文学会桑基图的画法
    db2备份与还原
    SAP R/3系统的启动和关闭
    重启sap过程
    DB2重启数据库实例
  • 原文地址:https://www.cnblogs.com/chuijingjing/p/9457601.html
Copyright © 2020-2023  润新知