• java中this关键字与this()基础用法


    一、this关键字

    this关键字最常用于构造方法中,初始化实例属性(和python中的self是一样的性质)

    class Dog {
        
        int age ;
        String name ;
        
        public Dog(int age, String name){
            
            //1、在构造方法中用于初始化参数(用于区分属性和入参)
            this.age =age;
            this.name =name;
        }
        
        public void demo(){
            System.out.println("demo执行");
        }
        
        public void demo1(){
            //在普通的实例方法中,可以添加this调用属性/方法
            this.age =1000;
            this.demo();
            
            //一般情况,我们调用实例属性/实例方法时不需要添加this,编译器会自动添加
            name ="小黑";
            demo();
        }
    }

    二、this()方法

    this()表示调用构造方法,此种调用只能用在构造方法中,即构造方法中调用构造方法this(实参)。

    1、this()、this(实参)必须方法构造方法的第一行

    2、在有参数构造方法中调用无参数构造方法this();在无参数的构造方法中调用有参数的构造方法this(实参)

    一、如下是无参数构造方法调用有参数构造方法:

    public class Constractor
    {
        int year;
        int month;
        int day;
        
        //无参数构造方法
        public Constractor()
        {
            this(2019,1,1);
        
        }
    
        //有参数构造方法
        Constractor(int year, int month, int day)
        {
            
            this.year = year;
            this.month = month;
            this.day = day;
        }
    
    }

    二、如下是有参数构造方法调用无参数构造方法:

    public class Constractor
    {
        int year;
        int month;
        int day;
        
        //无参数构造方法
        public Constractor()
        {
        
        }
    
        //有参数构造方法
        Constractor(int year, int month, int day)
        {
            this();
            
            this.year = year;
            this.month = month;
            this.day = day;
        }
    
    }

     三、this()/this(实参)必须出现在构造方法的第一行,否则报错

  • 相关阅读:
    消息队列如何测试
    服务宕机问题排查记录
    element UI table
    CMake进行C/C++开发(linux下)
    Nanodet模型部署(ncnn,openvino)/YOLOX部署(TensorRT)
    安装docker报错:Failed to listen on Docker Socket for the API 头条号
    JZ071把数字翻译成字符串
    JZ068打印从 1 到最大的 n 位数
    JZ072礼物的最大价值
    JZ076树中两个节点的最低公共祖先
  • 原文地址:https://www.cnblogs.com/jesse-zhao/p/10660439.html
Copyright © 2020-2023  润新知