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(实参)必须出现在构造方法的第一行,否则报错

原文地址:https://www.cnblogs.com/jesse-zhao/p/10660439.html