zoukankan      html  css  js  c++  java
  • 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 放在一起讲,见下面

  • 相关阅读:
    Stm32设置串口300波特率
    STM32F103ZET6移植FreeRTOS过程
    什么时候该用裸机?什么时候该用RTOS?
    又到了立flag时间
    关于掉电数据保存的心得
    一个教训
    下个月回国给自己定目标
    GPRS模块/4G开发过程
    ftp登陆失败,check pass; user unknown
    python深浅拷贝
  • 原文地址:https://www.cnblogs.com/chuijingjing/p/9457601.html
Copyright © 2011-2022 走看看