zoukankan      html  css  js  c++  java
  • 《Java基础知识》Java this关键字详解

    this 关键字用来表示当前对象本身,或当前类的一个实例,通过this可以调用对象的所有方法和属性。

    例如:

    public class Demo {
        private int x = 10;
        private int y = 15;
    
        public void sum(){
            //通过this获取成员变量,this可以省略。
            int z = this.x + this.y;   
            System.out.println("x+y = "+z);
        }
    
        public static void main(String[] args) {
            Demo demo = new Demo();
            demo.sum();
        }
    }

    运行结果:

    使用this区分同名变量

    public class Demo {
        private String name;
        private int age;
    
        public Demo(String name,int age){
            //this不能省略,this.name 指的是成员变量, 等于后面的name 是传入参数的变量,this可以很好的区分两个变量名一样的情况。
            this.name = name;
            this.age = age;
        }
        public static void main(String[] args){
            Demo demo = new Demo("微学院",3);
            System.out.println(demo.name + "的年龄是" + demo.age);
        }
    }

    运行结果:

    this作为方法名来初始化对象

    public class Demo {
        private String name;
        private int age;
    
        public Demo(){
            /**
             * 构造方法中调用另一个构造方法,调用动作必须置于最起始位置。
             * 不能在构造方法之外调用构造方法。
             * 一个构造方法只能调用一个构造方法。
             */
            this("微学院",3);
        }
    
        public Demo(String name,int age){
            this.name = name;
            this.age = age;
        }
    
        public static void main(String[] args){
            Demo demo = new Demo();
            System.out.println(demo.name + "的年龄是" + demo.age);
        }
    }

    运行结果:

     this作为参数传递

    class Person{    
        public void eat(Apple apple){
            Apple peeled = apple.getPeeled();
            System.out.println("Yummy");
        }
    }
    class Peeler{
        static Apple peel(Apple apple){
            return apple;
        }
    }
    class Apple{
        Apple getPeeled(){
            //传入this,就是传入Apple。
            return Peeler.peel(this);
        }
    }
    public class This{
        public static void main(String args[]){
            new Person().eat(new Apple());
        }
    }

    this 用法就到这里。

    参考:https://www.cnblogs.com/yefengyu/p/4821582.html

    This moment will nap, you will have a dream; But this moment study,you will interpret a dream.
  • 相关阅读:
    Vue3.0 是如何变得更快的?
    阿里云 Centos7 安装mongodb
    ASP.Net Core5.0 EF Core使用记录
    MongoDB批量更新|按条件更新SQL|批量删除某个字段
    Layui单元格编辑获取修改前的值
    判断字符串出现的多个位置
    原生JavaScript的DOM操作汇总
    @Value值为null、#和$的区别
    Dubbo推荐用法
    Dubbo 服务化最佳实践
  • 原文地址:https://www.cnblogs.com/jssj/p/11323948.html
Copyright © 2011-2022 走看看