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 放在一起讲,见下面

  • 相关阅读:
    Scala(二)——基础语法(与Java的区分)和函数式编程
    LeetCode3.无重复字符的最大子串
    LeetCode2.两数相加
    LeetCode1.两数之和
    Scala(一)——基本类型
    图论算法总结(一)——图的遍历
    Hutool强大的工具类
    Jdk8新特性之接口新增方法
    mybatis的xml配置中if text判断
    Jdk8新特性目录
  • 原文地址:https://www.cnblogs.com/chuijingjing/p/9457601.html
Copyright © 2011-2022 走看看