• Java基础this关键字02


    需求:当程序员调用以下无参数的构造方法的时候,默认创建的日期是“1971-9-1”

    this可以用在哪里:

    • 1.可以使用在实例方法当中,代表当前对象【语法格式this.】
    • 2.可以使用在构造方法当中,通过当前的构造方法调用其它的构造方法【语法格式:this(实参);】
    • 重点记忆:this()这种语法只能出现在构造函数第一行

    代码:

    public class Date {
    	private int year;
    	private int month;
    	private int day;
    
    	public Date(int year,int month,int day){
    		this.year = year;
    		this.month = month;
    		this.day = day;
    	}
    	
    	public Date(){
    		/*this.year = 1971;
    		this.month = 9;
    		this.day = 1;*/
    		
    		//以上代码可以通过调用另一个构造方法来完成
    		//但前提是不能创建新的对象。以下代码表示创建了一个全新的对象
    		
    		//需要采用以下的语法来完成构造方法的调用
    		//这种方式不会创建新的java对象。但同时又可以达到调用其它的构造方法
    		this(1971,9,1);
    	}
    
    	public int getYear() {
    		return year;
    	}
    
    	public void setYear(int year) {
    		// 设立关卡(有时间可以设立关卡)
    		this.year = year;
    	}
    
    	public int getMonth() {
    		return month;
    	}
    
    	public void setMonth(int month) {
    		// 设立关卡(有时间可以设立关卡)
    		this.month = month;
    	}
    
    	public int getDay() {
    		return day;
    	}
    
    	public void setDay(int day) {
    		// 设立关卡(有时间可以设立关卡)
    		this.day = day;
    	}
    	
    	public void print(){
    		System.out.println(this.year + "年" + this.month + "月" + this.day + "日");
    	}
    	
    	
    	
    }
    public class DateTest {
    
    	public static void main(String[] args) {
    		
    	   //创建日期对象1
    		Date time1 = new Date();
    		time1.print();
    		
    	   //创建日期对象2
    		Date time2 = new Date(2022,8,1);
    		time2.print();
    
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
  • 相关阅读:
    一分钟get✔一个文献阅读的最核心技巧(用的是小绿鲸文献阅读器)
    数据结构-----串(String)详解
    Margin Based Loss
    想画一张版权属于你的图吗?AI作画,你也可以
    建立Logistic模型进行分析--课后习题3(多元统计分析)
    CVE-2021-4034 polkit提权漏洞复现
    MMoE: 基于多门专家混合的多任务学习任务关系建模
    39、HumanNeRF
    ClickHouse 复制粘贴多行sql语句报错
    TS的类型规则 类型排名
  • 原文地址:https://blog.csdn.net/qq_46096136/article/details/126110765